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.
Analyse: set two pointers, index1 and index2. When index2 is less than the length of the string, check interval s[index1...index2] and find whether there is duplicate number with s[index2]. If yes, index1++, else index2++. Remember to update the result.
Runtime: 20ms.
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 if(s.length() <= 1) return s.length(); 5 6 int index1 = 0, index2 = 1; 7 int result = INT_MIN; 8 for(; index2 < s.length(); index2++){ 9 for(int i = index1; i < index2; i++){ 10 if(s[i] == s[index2]){ 11 index1 = i + 1; 12 break; 13 } 14 } 15 result = max(result, index2 - index1 + 1); 16 } 17 return result; 18 } 19 };
时间: 2024-12-06 04:44:50