给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
解法:
滑动窗口+hashset,左指针移动则删除,右指针移动则添加
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> us;
int n = s.size();
int ed = -1;
int mx = 0;
for(int i=0;i<n;++i){
if(i!=0){
us.erase(s[i-1]);
}
while(ed+1<n&&!us.count(s[ed+1])){
us.insert(s[ed+1]);
++ed;
}
mx = max(mx,ed-i+1);
}
return mx;
}
};
给你两个字符串 s1 和 s2 ,写一个函数来判断 s2 是否包含 s1 的排列。如果是,返回 true ;否则,返回 false 。
换句话说,s1 的排列之一是 s2 的 子串 。
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int n1=s1.size();
int n2=s2.size();
if(n1>n2){
return false;
}
unordered_map<char,int> um;
int st=0;
int ed=st+n1-1;//[st,ed]
for(int i=st;i<=ed;++i){
um[s2[i]]++;
}
while(st<=n2-n1){
bool sg = true;
auto tp = um;
for(int j=0;j<n1;++j){
if(tp[s1[j]]==0){
sg = false;
break;
}else{
tp[s1[j]]--;
}
}
if(sg){
return true;
}
um[s2[st]]--;
++st;
um[s2[ed+1]]++;
++ed;
}
return false;
}
};