题目描述:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be asubstring, "pwke"
is a subsequence and not a substring.
给定一个字符串,求不包含重复字符的最长子串(连续的字符)的长度。
解题思路:
要使得子串中不包含重复的字符,可以考虑将字符串从头扫到尾,用一个布尔数组记录当前子串使用的字符,这样可以避免每次生成一个子串后重新判断是否有重复字符。
使用布尔数组的时间复杂度为O(1);若使用STL的set,时间复杂度为O(log(n)).
使用一个队列记录子串的字符,每次读取字符串中的一个字符时,判断之前构成的子串是否包含这个字符。若包含,则将队列中的首字符弹出,相当于删掉当前的子串的前缀。最后将新字符加入子串中。
参考代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
bool vis[512];
memset(vis,0,sizeof(vis));
queue<char> q;
int maxLen = 0;
for (char c:s){
while(vis[c]){
char x = q.front();
q.pop();
vis[x] = false;
}
vis[c] = true;
q.push(c);
if (q.size() > maxLen)maxLen = q.size();
}
return maxLen;
}
};