求最大无重复子串长度

参考链接

这里只需要注意一下from的跳转即可,每次跳转的序号为to指向的字符在子串中出现的位置 + 1。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        int from = 0;
        int to = 0;
        int length = 1;
        int maxLength = 1;

        while (to < s.length()) {
            int site = s.substring(from, to).indexOf(s.charAt(to));
            if (site != -1) {
                length = to - from;
                if (length > maxLength) maxLength = length;
                from = from + site + 1;
            }
            to ++;
        }

        if (to - from > maxLength) {
            maxLength = to - from;
        }

        return maxLength;
    }
}

public class LengthOfLongestSubstring {

    public static int lengthOfLongestSubstring(String s) {
        /**
         * left、right用于最后打印子串是什么,如果只是求最大无重复子串的长度,则可以不用这两个变量
         */
        int left = 0; int right = 0;


        if (s == null || s.length() == 0) return 0;
        int from = 0;
        int to = 1;
        int length = 1;
        int maxLength = 1;

        /**
         * to 遍历直到末尾
         */
        while (to < s.length()) {
            int site = s.substring(from, to).indexOf(s.charAt(to));
            if (site != -1) {
                length = to - from;
                if (length > maxLength) {
                    maxLength = length;

                    /**
                     * 保留最大子串的左右下标,用于最后取出最大无重复子串,若只求子串最大长度,则这个逻辑可以不要
                     */
                    left = from;
                    right = to;
                }

                from = from + site + 1;
            }

            to ++;
        }

        /**
         * 处理最后子串
         */

        
        if (to - from > maxLength) maxLength = to - from;

        System.out.println(s.substring(left, right));
        return maxLength;

    }

    public static void main(String arr[]) {
        String s = "abccd";
        int maxLength = lengthOfLongestSubstring(s);
        System.out.println(maxLength);
    }


}

【LeetCode】无重复字符串最长子串 - 弗兰克的猫 - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值