Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”,
T is "ece" which its length is 3.
public int lengthOfLongestSubstringTwoDistinct(String s) {
Map<Character, Integer> map = new HashMap<>();
int start = 0, end = 0, maxLength = 0, cnt = 0;
while (end < s.length()) {
char c = s.charAt(end);
map.put(c, map.getOrDefault(c, 0) + 1);
if (map.get(c) == 1) cnt++;
end++;
while (cnt > 2) {
char tmp = s.charAt(start);
map.put(tmp, map.get(tmp) - 1);
if (map.get(tmp) == 0) cnt--;
start++;
}
maxLength = Math.max(maxLength, end - start);
}
return maxLength;
}
本文介绍了一种求解字符串中最长包含至多两种不同字符的子串长度的算法实现。通过滑动窗口与哈希映射相结合的方法,有效地解决了这一问题,并提供了完整的Java代码示例。
702

被折叠的 条评论
为什么被折叠?



