这题目是简化版的最小覆盖子串 ,基本上思路是一致的,右指针移动,根据右指针碰到的情况来考虑是否移动左指针和计算结果。
二刷最小覆盖子串的时候会写一下blog。
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] map = new char[128];
// current char in the window
int count = 0;
// left pointer
int start = 0;
int result = 0;
// i rightPtr
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i); // O(1) for string literal
// repeat occur
if (map[c] == 1) {
// move left ptr until map[c] = 0
while (map[c] != 0) {
// Note: s.charAt(start) not start
map[s.charAt(start)] = 0;
start++;
count--;
}
}
// first occur
// Note: this check should put after map[c] == 1, because we have to process current char c after moving left pointer(start)
if (map[c] == 0) {
map[c] = 1;
count++;
}
// calculate the length of current substring
result = Math.max(result, count);
}
return result;
}
}