- 设置两个
pointer,start指向子串的起始位置,end指向子串的终止位置。
- 设置一个
HashMap,保存字符和该字符出现的在字符串中的位置。
- 当
HashMap中已经存在某个字符,并且该字符在字符串中出现的位置在start之后,说明出现了重复字符。
- 更新最大子串的长度
max。
- 更新
HashMap中该重复字符出现在字符串的位置,即end。
Implementation
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int start = 0;
int max = 0;
for (int end = 0; end < s.length(); end++) {
char ch = s.charAt(end);
if (map.containsKey(ch) && map.get(ch) >= start) {
max = (max < end - start? end - start: max);
start = map.get(ch) + 1;
}
map.put(ch, end);
}
return max < s.length() - start? s.length() - start: max;
}
}