美文网首页
Longest Substring Without Repeat

Longest Substring Without Repeat

作者: Aptitude | 来源:发表于2019-06-17 20:32 被阅读0次

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

    Example 1:
    Input: "abcabcbb"
    Output: 3
    Explanation: The answer is "abc", with the length of 3.
    Example 2:
    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    Example 3:
    Input: "pwwkew"
    Output: 3
    Explanation: 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.

    这道题开始的思路复杂度为n^2,想法是外层循环控制总方向,内存循环控制外层循环定位的方向,结果是运行时间超时。看了别人的解法之后,发现可以是n来实现,只有一层循环控制,并且可以步进移动。当碰到有重复的字符时,直接跳到重复的值索引后一位,然后继续寻找,因此就是如下解法。

    class Solution {
    public:   
        int lengthOfLongestSubstring(string s) {     
            if(s.empty())
                return 0;
            int i,maxLength = 0;
            string temp;
            for(i=0;i<strlen(s.c_str());i++){
                if(temp.find(s[i]!=temp.npos)){
                    temp = temp.substr(temp.find(s[i])+1,strlen(temp.c_str()));
                }
                temp = temp + s[i];
                maxLength = max(maxLength,strlen(temp.c_str()));
            }  
            return maxLength;
        }
        int max(int a,int b){
            return a>b?a:b;
        }
    };
    

    相关文章

      网友评论

          本文标题:Longest Substring Without Repeat

          本文链接:https://www.haomeiwen.com/subject/dzrzfctx.html