题目要求最大的不重复字串的长度。很明显,滑动窗口法可以很好地解决:i,j为滑动窗口的界,从j开始进行索引,如果charAt(j)出现在substring(i,j+1)中,记出现的位置为j',将i变为j'+1,计算长度。
方法一:运用数组,一步一步地移动i到指定位置。(先计数,再判断)
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] map = new int[256];
int max = 0;
int left = 0;
for(int right = 0; right < s.length(); right++) {
//计数
map[s.charAt(right)]++;
while(map[s.charAt(right)] > 1) {
map[s.charAt(left)]--;
left++;
}
max = Math.max(max,right - left + 1);
}
return max;
}
}
方法二:运用HashMap对法一进行优化 (因为加入map会覆盖以前的映射值,所以先判断,在加入)
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
int max = 0;
int start = 0;
for(int i=0; i<s.length();i++){
if(map.containsKey(s.charAt(i))){
start= Math.max(start,map.get(s.charAt(i))+1);
}
//加入map
map.put(s.charAt(i),i);
max = Math.max(max,i-start+1);
}
return max;
}
}