给定一个字符串 s ,找出 至多 包含两个不同字符的最长子串 t ,并返回该子串的长度。
示例 1:
输入: "eceba"
输出: 3
解释: t 是 "ece",长度为3。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Scanner;
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int[] cnt = new int[256];
int ret = 0;
int sum = 0;
int left = 0, right = 0;
while (right < s.length()) {
cnt[s.charAt(right)]++;
if (cnt[s.charAt(right)] == 1) {
sum++;
if (sum == 3) {
ret = Math.max(ret, right - left);
while (sum > 2) {
cnt[s.charAt(left)]--;
if (cnt[s.charAt(left++)] == 0) {
sum--;
}
}
}
}
right++;
}
ret = Math.max(ret, s.length() - left);
return ret;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(new Solution().lengthOfLongestSubstringTwoDistinct(in.next()));
}
}
}