AC cpp solution


  • 1
    G

    basic idea is to use 2 pointers to keep the current longest substring

    class Solution {

    public:
    	int lengthOfLongestSubstringTwoDistinct(string s) 
    	{
    		if(s.size()==0) return 0;
    		if(s.size()==1) return 1;
    
            unordered_set<char> map;
    		int p=0;
    		int q=1;
    		int max=INT_MIN;
    		map.insert(s[p]);
    
    		while(q<s.size())
    		{
    			if(map.find(s[q])==map.end())
    			{
    				if(map.size()==2)
    				{
    					map.clear();
    
    					int t=q-1;
    					while(s[t-1]==s[t]) t--;
    					p=t;
    				}
    
    				map.insert(s[q]);
    				map.insert(s[p]);
    			}
    
    			q++;
    			if(q-p>max) max=q-p;
    		}
    
    		return max;
        }
    };

  • 0

    best best best solution


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.