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),但是常數因子會小很多;