题目:
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.
思路:Minimum window substring的简化版,双指针记录window范围,用一个map(实际是数组)来存每个字符的个数。需要注意的是为了减少更新最大长度的运行次数,仅在每次开始缩小窗口的时候才更新。对于始终不需要缩小窗口的情况,仅需要再最后再更新一次即可。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() <= 0) return 0;
vector<int> record(256, 0);
int max_length = 1;
int front = 0;
int back = 0;
for (front = 0; front < (int)s.size(); ++front) {
record[s[front]]++; //expand the window
if (record[s[front]] > 1) { //meet duplicates
max_length = max_length > (front - back) ? max_length : front - back; //update max
for (; record[s[front]] > 1 && back < front; back++) { //shrink the window
if (record[s[back]] > 0) {
record[s[back]]--;
}
}
}
}
max_length = max_length > (front - back) ? max_length : front - back;
return max_length;
}
};
总结:每个字符被两个指针访问一次,复杂度为O(n).