leetcode--最长非重复子序列--O(n)--基于队列

该博客探讨了一种使用队列解决LeetCode中寻找字符串最长不重复子序列问题的方法。通过O(n)的时间复杂度,找到给定字符串中无重复字符的最长子串,例如在字符串'abcabcbb'中最长子串为'abc',长度为3;在字符串'bbbbb'中,最长子串为'b',长度为1。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值