Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
class Solution {
public int lengthOfLongestSubstring(String s) {
int n=s.length();
Map<Character,Integer> m=new HashMap<>();
int ans=0;
for(int i=0,j=0;j<n;j++){
if(m.containsKey(s.charAt(j))){
i=Math.max(m.get(s.charAt(j)),i);//1
}
ans=Math.max(ans,j-i+1);
m.put(s.charAt(j),j+1);
}
return ans;
}
}
注意:1标志处。
当i进行了跳跃的时候,并没有在map中处理被跳跃的那些char,所以一种方法是将那些方法处理掉,另一种方法就是根据没有处理的那些char会在程序哪里发生作用,然后根据其特征采用方法将其直接忽视即可,,,此处就是采用了大小的特征将其忽视了。