Longest Substring Without Repeating Characters
2017-12-05 13:25
246 查看
这个我一开始想复杂了,总想着先记录出字符串再算个数,结果把自己套里了,百思不得其解索性百度了。
百度出的几种结果主流来说一种是hashmap,这种我改了字符串发现不大对,于是找到一个C++的答案,是用数组计数的方式,通过每次取最大值并记录当前字符串,这种方法简约但不能记录得到解的字符串略有不足,不过符合题意,读了差不多五遍才明白其中深意。
48ms
public int lengthOfLongestSubstring(String s) {
char[] ss = s.toCharArray();//如果是C++ 就没那么麻烦可以直接用了
int[] m = new int[256];//记录m[a],m[b]在数组中最新的位数,如c在第四位,b从第一位不断被更新直到第八位数组末尾
int res = 0;//个数
int left = 0;//字符串起点
for(int i=0;i < ss.length;++i){//此处是i++也可以
if(m[ss[i]] == 0 || m[ss[i]] < left){//s[i]位置的字符没有过或者在本次起点以前有过都可计入当前字符串长度
res = Math.max(res,i-left+1);//res计数保留最大,在据本次起点的字符串个数i-left+1和当前最大中取最大值
}else{//更新字符串的起点
left = m[ss[i]];
}
m[ss[i]] = i+1;
}
return res;
}
百度出的几种结果主流来说一种是hashmap,这种我改了字符串发现不大对,于是找到一个C++的答案,是用数组计数的方式,通过每次取最大值并记录当前字符串,这种方法简约但不能记录得到解的字符串略有不足,不过符合题意,读了差不多五遍才明白其中深意。
48ms
public int lengthOfLongestSubstring(String s) {
char[] ss = s.toCharArray();//如果是C++ 就没那么麻烦可以直接用了
int[] m = new int[256];//记录m[a],m[b]在数组中最新的位数,如c在第四位,b从第一位不断被更新直到第八位数组末尾
int res = 0;//个数
int left = 0;//字符串起点
for(int i=0;i < ss.length;++i){//此处是i++也可以
if(m[ss[i]] == 0 || m[ss[i]] < left){//s[i]位置的字符没有过或者在本次起点以前有过都可计入当前字符串长度
res = Math.max(res,i-left+1);//res计数保留最大,在据本次起点的字符串个数i-left+1和当前最大中取最大值
}else{//更新字符串的起点
left = m[ss[i]];
}
m[ss[i]] = i+1;
}
return res;
}
相关文章推荐
- LeetCode题解 #3 Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode OJ - Longest Substring Without Repeating Characters
- [leetcode 3] Longest Substring Without Repeating Characters
- LeetCode : Longest Substring Without Repeating Characters [java]
- leetcode 149 Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- leetcode:Longest Substring Without Repeating Characters
- leetcode第七题----- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- HashTable-3-Longest Substring Without Repeating Characters
- #3 longest-substring-without-repeating-characters
- LeetCode 第三题,Longest Substring Without Repeating Characters
- leetcode-3-Longest Substring Without Repeating Characters
- 【leetcode】Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- LeetCode No.3 Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- 【Leet Code】Longest Substring Without Repeating Characters