• 剑指 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;
        }
    }
    
  • 相关阅读:
    176. Second Highest Salary
    175. Combine Two Tables
    172. Factorial Trailing Zeroes
    171. Excel Sheet Column Number
    169. Majority Element
    168. Excel Sheet Column Title
    167. Two Sum II
    160. Intersection of Two Linked Lists
    个人博客记录
    <meta>标签
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859942.html
Copyright © 2020-2023  润新知