Ref: http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html
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.
[解题思路]
从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。这时需要清空Map,并且从index+1开始重新进行搜索。
比如
直到扫描到最后一个字母。
代码用Java 重写如下:
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
//http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html
// 使用hashmap 来记录各个字符最后出现的位置,如果之前出现过,则需要将窗口在前面截断,否则当前长度
// 应该在上一个长度加1;
int len = s.length();
int max = 0;
int last = 0;
HashMap
h = new HashMap
();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (h.containsKey(c)) {
// go back the the last index and count again.
i = h.get(c);
h.clear();
last = 0;
continue;
} else {
last++;
}
h.put(s.charAt(i), i);
max = Math.max(max, last);
}
return max;
}
}
Solution 2:
优化后,使用一个start来记录起始的index,判断在hash时 顺便判断一下那个重复的字母是不是在index之后。这样可以避免hash的clear和重建操作,也不需要退回前面去重新计算和加入map。
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
//http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html
// 使用hashmap 来记录各个字符最后出现的位置,如果之前出现过,则需要将窗口在前面截断,否则当前长度
// 应该在上一个长度加1;
int len = s.length();
int max = 0;
int last = 0;
int start = 0;
HashMap
h = new HashMap
();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (h.containsKey(c) && h.get(c) >= start) {
// go back the the last index and count again.
start = h.get(c) + 1;
last = i - start;
}
last++;
h.put(s.charAt(i), i);
max = Math.max(max, last);
}
return max;
}
}