题目描述:给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
学习:
用unordered_map暴力破解,unordered_set 容器,不再以键值对的形式存储数据,而是直接存储数据的值 ;容器内部存储的各个元素的值都互不相等,且不能被修改;不会对内部存储的数据进行排序。empty(),find(),insert(),count(),erase()
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int result=0;
for(int i=0;i<s.length();i++)
{
unordered_set<char> st;
int temp=0;
for(int j=i;j<s.length();j++)
{
if(st.count(s[j])==0)
{
st.insert(s[j]);
temp++;
}
else
{
break;
}
}
if(temp>result)
{
result=temp;
}
}
return result;
}
};
答案给的题解也差不多,用滑动窗口来做的,结合两个指针,其实和我的也差不多(或许
评论1:答案有个缺点,左指针并不需要依次递增,即多了很多无谓的循环。 发现有重复字符时,可以直接把左指针移动到第一个重复字符的下一个位置即可。评论2:标准答案步骤稍多,而且不容易理解,应该左侧指针固定,移动右侧指针,当窗口内最右侧的字符在set中存在时,左侧指针移动并从set中移除原左侧指针对应的字符,这样再取窗口长度的最大值即可。
很有道理,比我每次都定义一个set要好多了,按照这个想法自己去写了下,就是判断右指针与当前集合中的元素是否有重,如果有重则需要把当前左指针的元素移出,一直到没有重复为止。例如abcdcefghi,当左指针在a有指针在第二个c处,判断有重,会将左指针所只的a移出,依然有重,则b移出,c移出,后没有重复则可将右指针的加入,以此实现滑动窗口。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int result=0;
unordered_set<char> st;//唯一集合
int left=0;int right=0;//左右指针
for(;right<s.length();right++)
{
while(st.count(s[right])==1)
{
st.erase(s[left]);
left++;
}
st.insert(s[right]);
int temp=right-left+1;
if(temp>result)
{
result=temp;
}
}
return result;
}
};
unordered_set,以下代码输出为2,所以没有重复
#include<iostream>
#include<unordered_set>
using namespace std;
int main()
{
unordered_set<int> s;
s.insert(4);
s.insert(3);
s.insert(3);
cout<<s.size()<<endl;
system("pause");
return 0;
}
顺便看看了unordered_map,输出为4,所以不让我们加捏
#include<iostream>
#include<unordered_map>
using namespace std;
int main()
{
unordered_map<char,int> p;
p.insert(pair<char,int>('u',4));
p.insert(pair<char,int>('u',3));
cout<<p['u']<<endl;
system("pause");
return 0;
}