3. Longest Substring Without Repeating Characters
340. Longest Substring with At Most K Distinct Characters
這兩道都是經(jīng)典題目,思路是sliding window + hashMap/HashSet.
具體3用HashSet, 340用HashMap。
題目不難,但不容易一次寫對。我在面試的時(shí)候就忘了一點(diǎn)。
下面分析一下這兩道題容易錯(cuò)的地方。
1。 分析各種情況時(shí),往往忘了在某個(gè)case把字母放入HashSet, 光記得刪了。
2。算長度時(shí)slow, fast pointer忘了+1 了。
3。 slow, fast pointer忘了移動了。。 為了避免出錯(cuò),最好把fast++放在循環(huán)的最后,但一開寫while loop就寫上。(用continue時(shí)要小心)
4。 Set, HashMap這些不要直接叫set, map的,要取有意義的名字,不然容易成為掛點(diǎn)
public int lengthOfLongestSubstringKDistinct(String s, int k) {
Map<Character, Integer> visitedTimes = new HashMap<>();
int ans = 0;
int slow = 0, fast = 0;
if (k == 0) return 0;
while (fast < s.length()) {
char ch = s.charAt(fast);
if (visitedTimes.containsKey(ch)) {
visitedTimes.put(ch, visitedTimes.get(ch) + 1);
} else if (visitedTimes.size() < k) {
visitedTimes.put(ch, 1);
} else {
while (slow < fast) {
char ch2 = s.charAt(slow++);
if (visitedTimes.get(ch2) == 1) {
visitedTimes.remove(ch2);
break;
} else {
visitedTimes.put(ch2, visitedTimes.get(ch2) - 1);
}
}
visitedTimes.put(ch, 1); //別忘了加這個(gè)。
}
ans = Math.max(fast - slow + 1, ans);
fast++; //一開寫while 就寫在這里,但要注意如果某次用了continue語句要++
}
return ans;
}
LC 3的代碼
public int lengthOfLongestSubstring(String s) {
Set<Character> visitedChars = new HashSet<>();
int slow = 0, fast = 0;
int ans = 0;
while (fast < s.length()) {
if (visitedChars.add(s.charAt(fast))) {
fast++;
ans = Math.max(ans, fast - slow);
} else {
while (s.charAt(slow) != s.charAt(fast)) {
visitedChars.remove(s.charAt(slow++));
}
slow++;
fast++;
}
}
return ans;
}