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

发布于 2024-07-25 09:51:43 字数 1778 浏览 50 评论 0

题目描述

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

假设字符串中只包含从 az 的字符。

解法

动态规划。

res[i] 表示以 s[i] 字符结尾的最长不重复字符串的长度。判断 s[i]

  • s[i] 在前面没出现过,那么 res[i] = res[i - 1] + 1
  • s[i] 在前面有出现过,判断它上一次出现的位置 indexi 的距离 dres[i - 1] 的大小关系:
    • d <= res[i - 1] ,说明它被包含在 res[i - 1] 构成的子串中,那么 res[i] = d
    • d > res[i - 1] ,说明它在 res[i - 1] 构成的子串的左侧,那么 res[i] = res[i - 1] + 1

需要用一个数组 t 记录一下当前出现的字符在哪个位置。

class Solution {
    /**
     * 最长不含重复字符的子字符串
     *
     * @param s 字符串
     * @return 最长不重复字符子串
     */
    public int longestSubstringWithoutDuplication(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        char[] chars = s.toCharArray();
        int[] t = new int[26];
        for (int i = 0; i < 26; ++i) {
            t[i] = -1;
        }
        t[chars[0] - 'a'] = 0;
        int n = chars.length;
        int[] res = new int[n];
        res[0] = 1;
        int max = res[0];
        for (int i = 1; i < n; ++i) {
            int index = t[chars[i] - 'a'];
            int d = i - index;
            res[i] = (index == -1 || d > res[i - 1])
                    ? res[i - 1] + 1
                    : d;

            t[chars[i] - 'a'] = i;
            max = Math.max(max, res[i]);
        }
        return max;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

刘备忘录

暂无简介

文章
评论
417 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文