给定一个字符串s,请你找出其中不含有重复字符的最长子串的长度。

目录

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;这句话的解释


 

  • 8
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值