Java 最长不含重复字符的子字符串详解

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

题目描述

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

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

解法

动态规划。

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

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

/**
 * @author bingo
 * @since 2018/12/8
 */

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;
    }
}

测试用例

  1. 功能测试(包含多个字符的字符串;只有一个字符的字符串;所有字符都唯一的字符串;所有字符都相同的字符串);
  2. 特殊输入测试(空字符串)。

教程来源于Github,感谢apachecn大佬的无私奉献,致敬!

技术教程推荐

10x程序员工作法 -〔郑晔〕

如何看懂一幅画 -〔罗桂霞〕

用户体验设计实战课 -〔相辉〕

人人都用得上的写作课 -〔涵柏〕

跟着高手学复盘 -〔张鹏〕

Spring编程常见错误50例 -〔傅健〕

李智慧 · 高并发架构实战课 -〔李智慧〕

Serverless进阶实战课 -〔静远〕

Rust 语言从入门到实战 -〔唐刚〕