欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

剑指 Offer 48. 最长不含重复字符的子字符串

程序员文章站 2022-07-14 08:08:04
...

剑指 Offer 48. 最长不含重复字符的子字符串

解法 动态规化

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.length() == 0) return 0;
        char[] chars = s.toCharArray();
        return lengthOfLongestSubstring(chars);
    }

    private int lengthOfLongestSubstring(char[] chars) {
        // f(i)代表以第i个字符结尾,不包含重复字符的子字符串的最大长度
        // 不含重复字符的子字符串的最大长度
        int maxLength = 0;
        // f(i-1)
        int curLength = 0;
        // 数组用于记录任意字符之前出现的位置,ASCII码表一个128个字符
        int[] position = new int[128];
        Arrays.fill(position,-1);
        for(int i = 0; i < chars.length; ++i) {
            // 第i个字符之前出现的位置
            int preIndex = position[chars[i]];
            // 第i个字符之前没有出现过,或者第i个字符与它上次出现位置的距离大于f(i-1)
            if(preIndex < 0 || i - preIndex > curLength) {
                curLength++;
            // 第i个字符出现在f(i-1)对应的子字符串之中
            }else { 
                if(curLength > maxLength)
                    maxLength = curLength;
                curLength = i - preIndex;
            }
            position[chars[i]] = i;
        }
        if(curLength > maxLength)
            maxLength = curLength;
        return maxLength;
    }
}
相关标签: LeetCode