其他分享
首页 > 其他分享> > 力扣 无重复字符的最长子串

力扣 无重复字符的最长子串

作者:互联网

题目:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

解题思路:

采用动态规划解法,dp[i]表示[0, i]这个区间,以s[i]为结尾的的最长子串的长度。那么

  1. dp[0] = 0, 只有一个字符时肯定不重复。
  2. i = 1 开始,遍历算dp[i], 有以下两种可能:①如果字符s[i]之前没有出现过,那么dp[i] = dp[i - 1] + 1;②如果字符s[i]之前出现过,设其之前出现时的下标为tmp,dp[i] = min(dp[i-1] + 1, i - tmp),因为dp[i]最大只能是dp[i - 1] + 1,若i - tmp比它大,证明在其中有另外的重复字符。
  3. 注意考虑,字符串为空时,直接返回0。

代码:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length() == 0) return 0;
        int[] dp = new int[s.length()];
        int mmax = 1;
        dp[0] = 1;
        Map<Character, Integer> map = new HashMap<>();
        map.put(s.charAt(0), 0);
        for(int i = 1; i < s.length(); i ++){
            Integer tmp = map.get(s.charAt(i));
            if(tmp != null){
                dp[i] = i - tmp;
                if(dp[i] > (dp[i-1] + 1)) {
                    dp[i] = dp[i-1] + 1;
                }
            }else {
                dp[i] = dp[i-1] + 1;
            }
            map.put(s.charAt(i), i);
            if(mmax < dp[i]){
                    mmax = dp[i];
                }
        }
        return mmax;
    }
}

标签:子串,tmp,字符,int,力扣,map,mmax,dp
来源: https://blog.csdn.net/qiao111_/article/details/122407932