剑指offer48 最长不重复子串 Java

无重复字符最长子串算法
本文介绍了一种用于寻找字符串中无重复字符的最长子串的算法实现。通过使用预索引数组记录字符上次出现的位置,算法可以高效地计算出最长无重复子串的长度。代码示例展示了算法的具体实现过程。
public class LongestSubStringWithoutDuplication48__ {
    public static void main(String[] args) {
        String str = "arabcacfr";
        System.out.println(subString(str));
        int i = 0;
        i = i ++;
        System.out.println(i);
    }

    private static int subString(String str) {
        if (str.length() <= 0) {
            return 0;
        }
        int[] preIndex = new int[26];
        Arrays.fill(preIndex, -1);
        int curLength = 0;
        int maxLength = 0;
        for (int i = 0; i < str.length(); i++) {
            char curChar = str.charAt(i);
            int curCharIndexInPreIndex = curChar - 'a';
            //与当前字符重复出现的字符的 上一次出现的位置
            int curCharPreIndex = preIndex[curCharIndexInPreIndex];
            //如果当前字符之前没得出现过,或者当前字符出现过 但是两次出现之间的距离大于 以前一个字符结尾的不重复子串的长度
            if (curCharPreIndex == -1 || i - curCharPreIndex > curLength) {
                curLength++;
            } else {
                //当前字符出现过并且两次出现的距离小于 以前一个字符结尾的不重复子串的长度
                maxLength = Math.max(maxLength, curLength);
                curLength = i - curCharPreIndex;
            }
            preIndex[curCharIndexInPreIndex] = i;
        }
        return Math.max(maxLength, curLength);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值