LeetCode|Longest Substring Without Repeating Characters

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode|Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

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.

 

我的第一种方案,

用一个变量LL记录从0到i-1位置中,以s[i-1]为末尾的substring的长度,

目标是计算L,也就是从0到i位置中,以s[i]为末尾的substring的长度。

递推关系也很简单,从s[i]开始回溯LL个位置,观察有没有字符与s[i]相同,如果相同则跳出回溯。回溯到的字符的个数就是L。

整个递推关系中用max来统计L的最大长度。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int l=(int)s.length();
        if(l==0)
            return 0;
        int L,LL;
        //LL represents the previous substring length
        //L represents the current substring length
        L=LL=1;
        int max=0;
        for(int i=1;i<l;i++)
        {
            int count=1;
            for(int j=i-1;j>=i-LL;j--)
            {
                if(s[j]!=s[i])
                    count++;
                else
                    break;
            }
            L=count;
            if(max<L)
                max=L;
            LL=L;
        }
        return max;
    }
};

 运算时间打败了40%的代码

以上是关于LeetCode|Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring

leetcode longest consecutive sequence

LeetCode Longest Increasing Subsequence

#Leetcode# 14. Longest Common Prefix