思路:
1.把string转为charArray,遍历char元素
2.使用set保存char,并判断是否包含当前遍历的元素
3.元素重复时,用当前set的长度,对比历史最大长度,确定最大长度
4.输出最大长度
import java.util.*;
public class Main{
//长度最长且不含有重复字符的子串
public static void check(String str){
if(str == null || str.trim().length() == 0){
return;
}
char[] arr = str.toCharArray();
int tmpMax = 0;
Set<Character> tmp = new HashSet<>();
for(char char1:arr){
// 包含重复字符时
if(tmp.contains(char1)){
// 对比set长度和历史最大长度,确定最大长度
if(tmpMax < tmp.size()){
tmpMax = tmp.size();
}
// 清空 set 重新开始
tmp.clear();
}
// set保存元素
tmp.add(char1);
}
// 遍历到结束时,再次比较set的长度和历史最大长度
if(tmpMax < tmp.size()){
tmpMax = tmp.size();
}
// 输出最大长度
System.out.println(tmpMax);
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String str = in.next();
check(str);
}
}
京公网安备 11010502036488号