图解
Longest Substring Without Repeating Characters
- 题意:找出字符串中没有重复字母的最大长度
- 难度:Medium
- 分类:Hash Table, Two Pointers, String
- 算法:两个指针,记录没有重复字母的子串的首和尾
public static int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> hm = new HashMap<>();
int max = 0;//记录窗口最大的长度
int j = 0;//左指针下标
for (int i = 0; i <s.length() ; i++) {
if(hm.containsKey(s.charAt(i))) {
j = Math.max(hm.get(s.charAt(i))+1,j);
/*
* 这里的j是滑动窗口的左边界,如果当前遍历到的字符从未出现过,则扩大右边界,
* 如果之前出现过,则分两种情况:
* 一种是该字符不在滑动窗口内,则左边界可以不变
* 一种是该字符在滑动窗口内,则要去除左边界的重复字符,可以将左边界加1
* 所以此处的方法可以完成上述要求
*/
//if input="abbabc"
//when i = 3, s.chatAt(3) == 'a' ,
//we will found last 'a' appears at index 0,
//but we should not update j from 2 ('b') to 0 ('a'),
//because here although the 'a' is in hashMap, but it appears before 'b'.
}
//i到j没有重复的字母,所以+1
//写到if外,因为可能该串本身就没有重复的字母,以及串首与串尾也要考虑
max = Math.max(i-j+1,max);
hm.put(s.charAt(i), i);
};
return max;
}
}