美文网首页
3. 无重复字符的最长子串

3. 无重复字符的最长子串

作者: 间歇性发呆 | 来源:发表于2019-11-16 23:57 被阅读0次

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

示例 1:

输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:最近学了动态规划,所以第一想法就是用动态规划解决,时间复杂度O(n)

class Solution {
    /**
     * 动态规划
     * 1. 状态定义:f(n) = 从index=0开始到index=n(必须包含)不含有重复字符的 最长子串
     * 2. 转移方程:f(n) = f(n - 1) + s.chatAt(n) || s.chatAt(n)
     *
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int max = 0, curMax = 0;
        // 从这个index开始的连续不重复字符
        int startIndex = 0;
        // 记录字符出现的最新index
        Map<Character, Integer> charIndexMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            // 当前的字符存在于之前连续的字符串当中
            if (charIndexMap.containsKey(s.charAt(i)) && charIndexMap.get(s.charAt(i)) >= startIndex) {
                startIndex = charIndexMap.get(s.charAt(i)) + 1;
                curMax = i - startIndex + 1;
            } else {
                curMax ++;
            }
            charIndexMap.put(s.charAt(i), i);
            if (curMax > max) {
                max = curMax;
            }
        }
        return max;
    }

    public static void main(String[] args) {
        int result = new Solution().lengthOfLongestSubstring("abcabcbb");
        System.out.println(result);
    }
}
运行效率

相关文章

网友评论

      本文标题:3. 无重复字符的最长子串

      本文链接:https://www.haomeiwen.com/subject/zfiuictx.html