代码:
public class Test {
public static void main(String[] args) {
System.out.println(getMaxStr("bbbdde"));
}
public static String getMaxStr(String s) {
// 最大值
int max = 0;
// 最长子串
String maxStr = "";
// 存储中间值
int num = 0;
// 存放字符集合
Set<Character> set = new HashSet<>();
// 遍历所有字符串
for (int i = 0; i < s.length(); i++) {
// 只要往里面放字符,那里面就会有一个,因此1个字符不能说明什么问题,当里面有两个字符的时候,说明就出现就有不重复的了
if (set.add(s.charAt(i)) && set.size() == 2) {
// 找出最大值
max = Math.max(max, num);
// 找出最长子串
if (max == num) {
maxStr = s.substring(i - max, i);
}
// 重置set
set = new HashSet<>();
// 由于已经重置了,所以还需要重新添加
set.add(s.charAt(i));
// 里面已经添加了一个,所以num是1
num = 1;
} else {
// 记录重复的数目
num++;
}
}
// 最终必须要和num在比较一次,应对最后几个都是重复的这种情况
max = Math.max(max, num);
// 找出最长子串
if (max == num) {
maxStr = s.substring(s.length() - max);
}
// 返回结果
return maxStr;
}
}
结果:
bbb
延伸:
1、给定一个字符串,请你找出其中不含有重复字符的最长子串的长度
2、给定一个字符串,请你找出其中不含有重复字符的最长子串
3、给定一个字符串,请你找出其中重复字符的最长子串的长度