54:最长不含重复字符的子字符串

最长不含重复字符的子字符串
public class Offer54 {
    public static void main(String[] args) {
        System.out.println(new Offer54().LongestSubStringWithoutDuplication("asfahjfabswr"));
    }


    public int LongestSubStringWithoutDuplication(String str) {
        if (str == null || str.length() == 0) return 0;
        int preLength = 0;
        int curLength = 0;
        int maxLength = 0;
        int[] pos = new int[26];
        for (int i = 0; i < pos.length; i++) {
            pos[i] = -1;
        }
        //1. 存在一个26长度的数组来保存a~z字符的上一次出现在str中位置下标
        //2. 判断字符重复出现问题,①:pos数组中的值为-1,未出现过;②:pos数组中的值不为-1,现在出现在str中的下标减去pos数组的下标大于现在子字符串的长度
        //3. 
        for (int i = 0; i < str.length(); i++) {
            // 获取字符的ASCII码
            int letterNumber = str.charAt(i) - 'a';
            //没有出现过 或者 子字符串的长度小于上次出现的距离
            if (pos[letterNumber] < 0 || i - pos[letterNumber] > preLength) {

                curLength = preLength + 1;
            } else {
                curLength = i - pos[letterNumber];
            }
            pos[letterNumber] = i;
            if (curLength > maxLength)
                maxLength = curLength;
            preLength = curLength;
        }


        return maxLength;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值