zoukankan      html  css  js  c++  java
  • 剑指 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;
        }
    }
    
  • 相关阅读:
    codevs1080线段树练习
    NOIP2015 子串
    codevs1204 寻找子串位置
    字符串匹配的KMP算法
    TYVJ1460 旅行
    基础
    搜索
    二叉排序树
    二叉树
    poj
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859942.html
Copyright © 2011-2022 走看看