您的位置:首页 > 其它

LeetCode-3. Longest Substring Without Repeating Characters

2016-04-01 18:53 295 查看
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.

这道题仔细想想其实不难的,最坏情况下,也就是所有都不重复的,时间复杂度会达到N平方。

最开始忘了加上break,导致超时~

后来上网看了一个帖子提供的思路 点击打开链接

发现和我的思想是一样的,回来看看忘了加break,在运行~就Ok~ 不过再仔细想想,还是他的更快一点。

public class Solution {
public int lengthOfLongestSubstring(String s) {
int count = 0;
int max=0;
HashSet<Character> set = new HashSet<Character>();
for(int j = 0 ; j<s.length(); j++){
for(int i = j ; i<s.length(); i++){
if(set.contains(s.charAt(i))){
if(count>max){
max=count;
}
set.clear();
count = 0;
break;         //
}
else{
set.add(s.charAt(i));
//	System.out.println(count);
count++;
}
}
}
if(count>max){
max=count;
}
return max;
}
}


这是我最开始的速度


后来按照博客中的方法改进了一下,于是....



人家的复杂度是N啊,好厉害

这是修改后的代码,主要改进在于循环加一后不用再重新寻找大部分不重复的子字符串。

public class Solution {
public int lengthOfLongestSubstring(String s) {
int count = 0;
int max=1;
boolean[] flags = new boolean[256];
int start=0;
int end=0;
if(s.length() ==0)
return 0;
while(end < s.length()){
if(flags[s.charAt(end)] == false){
flags[s.charAt(end)] = true;
end++;
}else{
flags[s.charAt(start)] = false;
count = end - start;
if(count>max){
max=count;
}
start++;
}

}
count = end - start;
if(count>max){
max=count;
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: