问题描述:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
样例输入:
ABCDABC
样例输出:
4
思路分析:
使用两个指针进行移动即可,一个哨兵,一个游标,并且要记录最大值。若找到重复字符串,则将哨兵直接移动到游标的位置,即可找到最长不重复字符串。
具体见代码注释:
import java.util.Scanner;
public class Wcfzczc {
//给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度
public static int lengthOfLongestSubstring(String s) {
int max=0;//定义最大值
for (int tt=0;tt<=s.length()-2;tt++) {
for (int ss=tt+1;ss<=s.length()-1;ss++) {
String temp1 = String.valueOf(s.charAt(ss));//定位当前字符
for (int i = ss-1; i >= tt; i--) {//循环判断重复字符
if (temp1.equals(String.valueOf(s.charAt(i))))//若在前面存在相同字符
{
int tempmax=ss-i;
if (tempmax>max)
max=tempmax;
tt=ss;//移动前面的指针
break;
} else {
int tempmax1 = ss - i +1;
if (tempmax1 > max)//大于当前max值进行更新
max = tempmax1;
}
if (ss==s.length()-1)
{
return max;
}
}
}
}
return max;
}
public static void main(String[] args) {
Scanner a=new Scanner(System.in);
String b=a.nextLine();
int out=lengthOfLongestSubstring(b);
System.out.println(out);
}
}
运行效果如下:
这中方法的时间复杂度还是比较高的,但是比较浅显易懂。大家也可以使用移动窗口的方法提高运行效率。