CODE 1 :Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
Solution
- 滑动窗口
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> occ;
int rp=-1,ans=0;
for(int i=0;i<s.size();i++){
if(i!=0){
occ.erase(s[i-1]);
}
while(rp+1<s.size()&& !occ.count(s[rp+1])){
occ.insert(s[rp+1]);
rp++;
}
ans=max(ans,rp-i+1);
}
return ans;
}
};
- 使用
unordered_set
储存元素以及对应的个数 - 在每次循环开始时,先剔除最前端的元素(第一次循环除外),因为以下while循环结束只有两种可能 :第一是元素个数大于一,第二是已经到达末尾。
- 下一个循环中每次插入rp所指的后一个,然后把rp向后移一个
- 最后储存ans和本次结果之中较大的一个
Code 2 :Permutation in String
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1’s permutations is the substring of s2.
Example 1
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Example 2
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
Solution
class Solution {
public:
bool checkInclusion(string s1, string s2) {
if(s1.size()>s2.size()) return false;
vector<int> count1(26);
vector<int> count2(26);
for(int i=0;i<s1.size();i++){
count1[s1[i]-'a']++;
count2[s2[i]-'a']++;
}
if (count1==count2) return true;
for(int i=s1.size();i<s2.size();i++){
count2[s2[i]-'a']++;
count2[s2[i-s1.size()]-'a']--;
if (count1==count2)
return true;
}
return false;
}
};
- 注意一开始的判断条件,如果
s1
比s2
短,就返回false
- 用
int
数组储存字母出现次数方便比较。 - 如果两个出现次数不相等,则
s2
剔除前一个,添入后一个,实现窗口的右移。