您的位置:首页 > 其它

【leetcode】Longest Substring Without Repeating Characters

2015-03-16 22:29 302 查看
问题描述:

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.csdn.net/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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: