You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
1. Use two pointers: start and end to represent a window.
2. Move end to find a valid window.
3. When a valid window is found, move start to find a smaller window.
publicStringminWindow(Strings, Stringt) {
int [] map = newint[128];
for (charc : t.toCharArray()) {
map[c]++;
}
intstart = 0, end = 0, minStart = 0, minLen = Integer.MAX_VALUE, counter = t.length();
while (end < s.length()) {
finalcharc1 = s.charAt(end);
if (map[c1] > 0) counter--;
map[c1]--;
end++;
while (counter == 0) {
if (minLen > end - start) {
minLen = end - start;
minStart = start;
}
finalcharc2 = s.charAt(start);
map[c2]++;
if (map[c2] > 0) counter++;
start++;
}
}
returnminLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen);
}
Longest Substring - at most K distinct characters
publicintlengthOfLongestSubstringKDistinct(Strings, intk) {
int[] map = newint[256];
intstart = 0, end = 0, maxLen = Integer.MIN_VALUE, counter = 0;
while (end < s.length()) {
finalcharc1 = s.charAt(end);
if (map[c1] == 0) counter++;
map[c1]++;
end++;
while (counter > k) {
finalcharc2 = s.charAt(start);
if (map[c2] == 1) counter--;
map[c2]--;
start++;
}
maxLen = Math.max(maxLen, end - start);
}
returnmaxLen;
}
Longest Substring - at most 2 distinct characters
publicintlengthOfLongestSubstringTwoDistinct(Strings) {
int[] map = newint[128];
intstart = 0, end = 0, maxLen = 0, counter = 0;
while (end < s.length()) {
finalcharc1 = s.charAt(end);
if (map[c1] == 0) counter++;
map[c1]++;
end++;
while (counter > 2) {
finalcharc2 = s.charAt(start);
if (map[c2] == 1) counter--;
map[c2]--;
start++;
}
maxLen = Math.max(maxLen, end - start);
}
returnmaxLen;
}
LongestSubstring - without repeating characters
publicintlengthOfLongestSubstring2(Strings) {
int[] map = newint[128];
intstart = 0, end = 0, maxLen = 0, counter = 0;
while (end < s.length()) {
finalcharc1 = s.charAt(end);
if (map[c1] > 0) counter++;
map[c1]++;
end++;
while (counter > 0) {
finalcharc2 = s.charAt(start);
if (map[c2] > 1) counter--;
map[c2]--;
start++;
}
maxLen = Math.max(maxLen, end - start);
}
returnmaxLen;
}