首页 > 代码库 > Leetcode#3 Longest Substring Without Repeating Characters

Leetcode#3 Longest Substring Without Repeating Characters

原题地址

 

双指针法。

右指针不断向右试探,当遇到重复字符时停下来,此时左指针开始向右收缩,直到去掉那个重复字符。

 

代码:

 1 int lengthOfLongestSubstring(string s) { 2         map<char, bool> record; 3         int maxLen = 0; 4         int l = 0; 5         int r = 0; 6          7         while (r < s.length()) { 8             while (r < s.length() && !record[s[r]]) { 9                 record[s[r]] = true;10                 r++;11             }12             maxLen = max(maxLen, r - l);13             while (s[l] != s[r]) {14                 record[s[l]] = false;15                 l++;16             }17             l++;18             r++;19         }20         21         return maxLen;22 }

 

Leetcode#3 Longest Substring Without Repeating Characters