leetcode--最長非重複子序列--O(n)--基於隊列

3. Longest Substring Without Repeating Characters
My Submissions
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),但是常數因子會小很多;

發佈了59 篇原創文章 · 獲贊 112 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章