题目描述:
Given a string, find the length of the longest substring without repeating characters.
例子:
Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given Given "abcabcbb", the answer is "abc", which the length is 3.
分析:
题意:给定一个字符串,找到最长的不重复连续子串并返回长度。
思路:考察双指针法和C++ set应用。我们用指针left,right分别表示需要查找子串的开始、结束位置,初始值均为0且按顺序遍历。①如果s[right]在set中出现,表明已经出现重复字符,此时s[left→right-1]为不重复字串,更新答案,从set中移除s[left],left加1(因为以left开始的最长不重复子串已经找到,left必须更新)。②如果s[right]在set中没出现,那么在set中加入s[right]、right加1,继续考察,如果right等于n,说明查找结束了,同时更新一次答案,最后返回最长长度。假设字符串长度为n,时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
// Exceptional Case:
if(n == 0){
return 0;
}
int left = 0, right = 0, ans = 0;
set<char> ss;
while(left <= right && right <= n - 1){
// debug
// cout << "l: " << left << ", r: " << right << endl;
if(ss.count(s[right])){
ans = max(ans, right - left);
ss.erase(s[left]);
left++;
}
else{
ss.insert(s[right]);
right++;
if(right == n){
ans = max(ans, n - left);
}
}
}
return ans;
}
};