LeetCode (3): Longest substring without repeating characters

Posted by ThunderAI on Mon, 06 Jan 2020 22:13:19 +0100

Title Description:

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

 

Example:

Given "abcabcbb", the longest substring without repeating characters is "abc", so the length is 3.

Given "bbbbb", the longest substring is "b", and the length is 1.

Given "pwwkew", the longest substring is "wke" and the length is 3. Note that the answer must be a substring, pwke is a substring, not a substring

 

Analysis:

Violence, traversal search and add methods, will all be compared. Set a temporary string to indicate the minimum string that has been used. Starting from the first character, the outer loop represents the string formed by the first character, and the inner loop represents all situations of the string formed by the first character. For example, abcabcbb, the first is abca, the second is bca... Wait. Next, look inside the inner loop to determine whether there are any characters to be added in the temporary string. Time complexity is higher than price, but can AC.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
          int length = 0;
        string next = "";
        if(s.size() == 1)
            return 1;
        if(s.size() == 0)
            return 0;
        
        for(int i=0;i<s.size()-1;i++){
        	string next = "";
            next += s[i];
            for(int j=i+1;j<s.size();j++){
                if(WhetherExistence(next,s[j]))  //And the next character don't want to wait
                {
                    next += s[j];
                    if((j==s.size()-1)&& j-i+1>length)
                    	length = j-i+1;
                }
                else{ 	
                    if(j-i>length)
                        length = j-i;
                     
                    break;
                }
                
            }
        }
        if(length==0)
            length = s.size();
       // cout<<next<<endl;
        return length;
    }
    
    
    int WhetherExistence(string s,char a){
        for(int i=0;i<s.size();i++)
        {
            if(s[i] == a)
                return 0;
        }
        return 1;
    }
};

 

Using map, the time complexity is O(n). Refer to the method in this paper: http://www.cnblogs.com/ariel-dreamland/p/8668286.html

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int res = 0, left = 0, i = 0, n = s.size();
        unordered_map<char, int> m;
        for (int i = 0; i < n; ++i) {
            left = max(left, m[s[i]]);
            m[s[i]] = i + 1;
            res = max(res, i - left + 1);
        }
        return res;
    }
};