目录
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串");
String s = sc.next();
int max = 0; // 标识最大长度
String s1 = s.substring(0, 1); // 截取第一个字符
for (int k = 1; k < s.length(); k++) {
char nextChar = s.charAt(k);
int index = s1.indexOf(nextChar);
if (index == -1) {
s1 = s1 + nextChar; // iushj
} else {
int len = s1.length();//5 3
if (len > max) {
max = len;
}
s1 = s1.substring(index + 1) + nextChar;
}
}
System.out.println(max);
}
}
结果:
请输入一个字符串
zahdsab
5
Process finished with exit code 0
二、代码分析
首先定义一个最大长度max并初始化为0;截取第一个元素,并命名为s1。
String s1 = s.substring(0, 1);
然后for循环依次往后遍历,使用charAt()方法取出相对应的字符命名为nextChar
char nextChar = s.charAt(k);
然后在s1中查找是否存在nextChar,使用indexOf()方法。(indexOf():返回指定字符在此字符串中第一次出现处的索引,如果没有找到返回-1)如果index == -1就说明在之前的字符串中不含有nextChar字符。
if (index == -1) {
s1 = s1 + nextChar;
}
else把最终s1的长度算出来和max对比。如果比max大就把s1.length的值赋给max。然后开始换元素,把前面的元素截取出来,从第一次出现重复的后面开始截取。在拼接nextChar
} else {
int len = s1.length();//5 3
if (len > max) {
max = len;
}
s1 = s1.substring(index + 1) + nextChar;
}
s1 = s1.substring(index + 1) + nextChar;这句话的解释