• LN : leetcode 3 Longest Substring Without Repeating Characters


    lc 3 Longest Substring Without Repeating Characters


    3 Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    1. Given "abcabcbb", the answer is "abc", which the length is 3.
    2. Given "bbbbb", the answer is "b", with the length of 1.
    3. Given "pwwkew", the answer is "wke", with the length of 3. Note that
      the answer must be a substring, "pwke" is a subsequence and not a
      substring.

    动态规划 Accepted##

    index数组用来标记该位是否第一次出现,invalid变量用来表示当前研究的子串头部的前一位,length用来表示当前研究的子串的长度。用动态规划的方法可以把时间复杂度降到最低的O(n)。

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            vector<int> index(256, -1);
            int length =0;
            for (int invalid = 0, i = 0; i < s.length(); i++) {
                invalid = max(index[s[i]]+1, invalid);
                index[s[i]] = i;
                length = max(length, i-invalid+1);
            }
            return length;
        }
    };
    
  • 相关阅读:
    每日总结2.26
    《梦断代码》阅读笔记三
    每日总结2.25
    每日总结2.24
    每日总结2.23
    每日总结2.22
    每日总结2.19
    《梦断代码》阅读笔记二
    Java-11 形参和实参
    Java-10 final用法
  • 原文地址:https://www.cnblogs.com/renleimlj/p/7647532.html
Copyright © 2020-2023  润新知