寻找最长不重复子串

package main.java.demo3;

import org.junit.Test;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
 *
 */
public class LengthOfLongestSubstring {

    /**
     * 解题思路:首先创建一个哈希表用来存储两个指针之间的字符,
     *         当遇到重复的字符时,从重复的字符之后重新开始计算.
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring_1(String s) {
        int result = 1;
        int currentBegin = 0;
        int currentResult = 0;
        Integer duplicate = 0;
        Map<String, Integer> hashMap = new HashMap();

        if(s.length() == 0) {
            return 0;
        }
        for(int i = 0; i < s.length(); i++) {
            String current = s.substring(i, i + 1);

            if((duplicate = hashMap.get(current)) != null) {
                currentResult = i - currentBegin;
                result = result > currentResult ? result : currentResult;
                currentBegin = duplicate + 1;
                i = currentBegin;
                currentResult = 0;
                hashMap = new HashMap();
                current = s.substring(i, i + 1);
            }

            hashMap.put(current, i);
            currentResult++;
        }

        return result > currentResult ? result : currentResult;
    }

    /**
     * 解题思路:上一个解法存在一定的问题,因为如果使用哈希表Map来存储,
     *          当遇到重复的字符时,无法将右指针指向当前正在进行的字符,
     *          因为Map无法删除重复字符左面的数据,然后下面的算法是对上个解法的改进,
     *          这次使用set集合来存储.
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring_2(String s) {
        Set<Character> characterSet = new HashSet<>();
        int length = s.length();
        if(length == 0) {
            return  0;
        }

        int rightPoint = 0;
        int currentBestResult = 0;

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

            while (rightPoint < length && !characterSet.contains(s.charAt(rightPoint))) {
                characterSet.add(s.charAt(rightPoint));
                rightPoint++;
            }
            currentBestResult = Math.max(currentBestResult, rightPoint - i);
            characterSet.remove(s.charAt(i));
        }

        return currentBestResult;

    }

    @Test
    public void subStringTest(){
        System.out.println(lengthOfLongestSubstring_1("dvdf"));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值