3. Longest Substring Without Repeating Characters
Total Accepted: 141293
Total Submissions: 646961
Difficulty: Medium
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.
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
#include <string>
#include <queue>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int record[128];
memset(record, 0, sizeof(int)* 128);
int maxLenth = 0;
queue<char> que;
for (auto iterTemp = s.begin(); iterTemp != s.end(); ++iterTemp)
{
char &charTemp = (*iterTemp);
if (record[(int(charTemp))])
{
//if have haved, add to queue, and pop the repeated one
while (que.front() != charTemp)
{
record[(int(que.front()))]--;
que.pop();
}
record[(int(que.front()))]--;
que.pop();
record[(int(charTemp))]++;
que.push(charTemp);
//record the maxLenth
maxLenth = maxLenth > que.size() ? maxLenth : que.size();
}
else//if do not repeat, add to queue
{
record[(int(charTemp))]++;
que.push(charTemp);
//record the maxLenth
maxLenth = maxLenth > que.size() ? maxLenth : que.size();
}
}
return maxLenth;
}
};
【说明】:这个方法写的复杂了,其实并不需要队列,只用一个数组记录下每个字符 在 string s 中最新的位置即可;就不重新写了,时间复杂度都是O(N),但是常数因子会小很多;