题目描述:
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
.
O(n) time
这题还是沿用two pointers的思路:用两个pointers l和r,初始时一直在string的头上。然后r开始走,并且把r走到的char都加入到一个map中:如果map中已经有了这个char,则通过l++来缩短substring,并且把l走到的char都从map中删去,直到map删去了这个重复的char。这就是没有重复char的substring之一,计算它的长度,并且和max_len取max。然后,r就又可以走下去,进行下一个循环了。
Mycode(AC = 17ms):
class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
int lengthOfLongestSubstring(string s) {
// write your code here
int helper[256] = {0,};
int l = 0, r = 0, max_len = 0;
while (r < s.length()) {
// add char into the map
helper[int(s[r])] += 1;
// delete char from start of substring
// if the s[r] is already in the map
while (helper[int(s[r])] > 1) {
helper[int(s[l++])] -= 1;
}
// increase r to find next substring
r++;
// get max length
max_len = max(max_len, r - l);
}
return max_len;
}
};