C++ O(n) Solution with Hash map


  • 0
    J
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int n = s.size();
            if(n==0) return 0;
            int start = 0;
            int maxlen=0;
            std::unordered_map<char, int> map;
            for(int i =0;i<n; i++){
                int len;
                char cur = s[i];
                if(map.find(cur)!= map.end())
                    start = max(start, map[cur]+1);
                
                len = i-start+1;
                
                if(len>maxlen) maxlen = len;
                map[cur]=i;
                    
            }
            return maxlen;
        }
    };

Log in to reply
 

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