每日一题
给定一个字符串 s ,找出 至多 包含两个不同字符的最长子串 t ,并返回该子串的长度。
示例 1:
输入: "eceba"输出: 3解释: t 是 "ece",长度为3。
示例 2:
输入: "ccaabbb"输出: 5解释: t 是 "aabbb",长度为5。
解题:滑动窗口
public class Day6 {
public static void main(String[] args) {
// int solution = new Day6().realSolution("aabbccc");
int solution = new Day6().realSolution("aabsbcccaiavvbb");
// int solution = new Day6().solution("eceba");
System.out.println(solution);
}
public int solution(String s) {
int max = 0;
int len = 0;
TreeSet<Character> set = new TreeSet<>();
for (int i = 0; i < s.length(); i++) {
set.clear();
len = 0;
set.add(s.charAt(i));
len++;
for (int j = i + 1; j < s.length(); j++) {
set.add(s.charAt(j));
if (set.size() > 2) {
break;
}
len++;
}
max = Math.max(max, len);
}
return max;
}
public int realSolution(String s) {
int max = 0, len;
char pre = ' ', post = ' ';
boolean flag;
for (int i = 0; i < s.length(); i++) {
len = 0;
flag = false;
pre = s.charAt(i);
len++;
for (int j = i + 1; j < s.length(); j++) {
if (s.charAt(j) != pre && !flag) {
post = s.charAt(j);
flag = true;
len++;
continue;
}
if (s.charAt(j) == pre || s.charAt(j) == post) {
len++;
} else {
break;
}
}
max = Math.max(max, len);
}
return max;
}
}