最长不含重复字符串
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
做法:使用HashMap记录每个字符最后一次出现的位置,如果出现重复的字符,就把当前字符上一次出现位置的下一个位置作为新起点,继续遍历
class Solution {
public int lengthOfLongestSubstring(String s) {
int max = 0;
int left = 0;
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
left = Math.max(left,map.get(c) + 1);
}
map.put(c,i);
max = Math.max(max,i - left + 1);
}
return max;
}
}