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
Constraints:
1 <= s1.length, s2.length <= 104
s1
ands2
consist of lowercase English letters.
题目:给定两个字符串,求s2中是否包含s1的排列。重要信息是只包含小写字符
思路:可用两个vector记录s1和s2子序列的小写字符个数。比较两个vector,如果相等则返回true,代码:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
if(s2.length() < s1.length()) return false;
vector<int> r1(26, 0), r2(26, 0);
for(int i = 0; i < s1.length()-1; i++){
r1[s1[i] - 'a'] ++;
r2[s2[i] - 'a'] ++;
}
r1[s1.back()-'a']++;
for(int i = s1.length()-1; i < s2.length(); i++){
r2[s2[i] - 'a'] ++;
if(i >= s1.length()) r2[s2[i-s1.length()] - 'a']--;
bool flag = true;
for(int j = 0; j<26; j++){
if(r1[j] != r2[j]){
flag = false;
break;
}
}
if(flag) return true;
}
return false;
}
};
time: O(N), space:O(1)