给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
package com.xuyinda;
import java.util.HashMap;
import java.util.List;
public class Solution {
public static int lengthOfLongestSubstring(String s) {
if(s==null){
return 0;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int left = 0;
int max = 0;
for(int i = 0; i <s.length();i++){
if(map.containsKey(s.charAt(i))) {
left = Math.max(left,map.get(s.charAt(i))+1);
}
//解释点一
map.put(s.charAt(i),i);
max = Math.max(max,i - left + 1);
//解释点二
}
return max;
}
}
Explanation 2 :It is easy to understand this part. (i-left+1) means the current window’s length. And the variable max represents the longest window’s length.
If the currrent window’s length is bigger than the last max, the value of max will be replaced by the bigger one.
Explanation 1 :If the new character repeats with the character in the map, the window’s left border will change. At first, I thought left = Math.max(map.get(s.charAt(i))+1) was enough. However, I missed one situation that the biggest index number of the character in the map might be smaller than the index number of current left border.
Summary:By resolving this question, I get a deep understanding of Hash Map and the algorithm of sliding window.