无重复字符的最长子串

无重复字符的最长子串

package com.example.demo.study.shuanfa;

import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;

/**
 * @Description: 无重复字符的最长子串
 * @ClassName: LongestSubstringWithoutRepeatingCharacters
 * @Author zhaomx
 * @Version 1.0
 * @Date 2021-06-29 14:04
 */
@Slf4j
public class LongestSubstringWithoutRepeatingCharacters {

    public static void main(String[] args) {
        String str = "abcddjhzndasad";

        int length = str.length();
        //定义左下标,由下标。最大不重复子串可看作是左两个下标进行滑动窗口对比
        int leftIndex = -1, rightIndex = 0, maxLength = 0;
        HashSet<Character> characterHashSet = new HashSet<Character>(length);

        for (int i = 0; i < length; i++) {

            //左侧下标向前移动,移除前一位字符
            if (i != 0) {
                characterHashSet.remove(str.charAt(i - 1));
            }

            //右侧下标不断向前移动,如果hashset中有重复字符,说明此刻已重复,跳出循环,否者将当前字符放入hashmap中
            while (rightIndex + 1 < length && !characterHashSet.contains(str.charAt(rightIndex + 1))) {
                characterHashSet.add(str.charAt(rightIndex + 1));
                rightIndex++;
            }
            //保留上一次与此次 子串长度最大的
            if (rightIndex - i + 1 > maxLength) {
                maxLength = rightIndex - i + 1;
                leftIndex = i;
            }
        }

        System.out.println("最大长度:" + maxLength + "字符串:" + str.substring(leftIndex, rightIndex - 1));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值