Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
思路:
看到这题我想了很多方法,最后思路很乱。其实想明白了没那么复杂。
1.用游标 i 从首到尾遍历字符串;
2.使用HashMap存储每个字母到目前为止最后出现的下标;
3.用max记录最大长度的不重复子串;
4.用游标 j 指向max所代表的子串的首字母;当 i 扫描到一个出现过的字符时,需要更新 j 的值。
public class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> lastIndexMap = new HashMap<>();
int max = 0;
for(int i = 0, j = 0; i < s.length(); i++){
if(lastIndexMap.containsKey(s.charAt(i))){
j = Math.max(j, lastIndexMap.get(s.charAt(i)) + 1);
}
lastIndexMap.put(s.charAt(i), i);
max = Math.max(max, i - j + 1);
}
return max;
}
}