Leetcode#3 Longest Substring Without Repeating Characters

时间:2015-01-29 19:20:25   收藏:0   阅读:140

原题地址

 

双指针法。

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

 

代码:

 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 }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!