Saturday, September 20, 2014

LeetCode: Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


   int lengthOfLongestSubstring(string s) {  
     int res = 0, start = 0;  
     int n = s.length();  
     vector<int> h(256, -1);  
   
     for (int i = 0; i < n; i++)  
     {  
       if (h[s[i]] != -1)  
       {  
         while(s[start] != s[i]){  
           h[s[start]] = -1;  
           start++;  
         }  
         start++;  
       }  
       else  
       {  
         if (res < i-start+1)res = i-start+1;  
         h[s[i]] = i;  
       }  
     }  
   
     return res;  
   }  

No comments:

Post a Comment