力扣3. 无重复字符的最长子串(滑动窗口、hashset)
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
滑动窗口
复杂度分析
时间复杂度:O(2n) = O(n),在最糟糕的情况下,每个字符将被 i 和 j 访问两次。
空间复杂度:O(min(m,n)),与之前的方法相同。滑动窗口法需要 O(k) 的空间,其中 k 表示 Set 的大小。而 Set 的大小取决于字符串 n 的大小以及字符集 / 字母 m 的大小。
#include "stdafx.h"
#include<string>
#include<vector>
#include <iostream>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;
class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
if (s.size() == 0)return 0;
set<char>window;
int left = 0;
int maxlen = 0;
for (int i = 0; i < s.size(); i++)
{
//找一个元素,如果容器中不存在该元素,返回值等于s.end()
//如果返回的不是s.end(),则说明还有重复,删除,窗口右移
while (window.find(s[i]) != window.end())
{
window.erase(s[left]);
left++;
}
//比较大小,看当前滑动窗口元素个数有没有多于之前的最大值
maxlen = max(maxlen, i - left + 1);
window.insert(s[i]);
}
return maxlen;
}
};
int main()
{
Solution ss;
string s = "pwwkew";
auto result = ss.lengthOfLongestSubstring(s);
return 0;
}
hashset用法
特点:无序,储存顺序与取出顺序不一致,唯一