问题描述:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
问题分析:见博客:http://blog.youkuaiyun.com/pickless/article/details/9018575
代码:
public int lengthOfLongestSubstring(String s) {
if(s==null || s.isEmpty()==true)
return 0;
Map<Character,Integer> map = new HashMap<Character,Integer>();
int start=0;
int end=1;
int max=1;
map.put(s.charAt(start), 0);
while(end<s.length()){
//当前元素没有出现过
if(!map.containsKey(s.charAt(end))){
//先给map中填充
map.put(s.charAt(end), end);
max=Math.max(max, end-start+1);
}else{
//当前元素出现了
if(map.get(s.charAt(end))>=start){
start=map.get(s.charAt(end))+1;
}
map.put(s.charAt(end),end);
max=Math.max(max, end-start+1);
}
end++;
}
return max;
}