【242】有效的字母异位词
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(),s.end());
sort(t.begin(),t.end());
if(s==t)
return true;
else
return false;
}
};
运用这个思路,继续做438题:找到字符串中的所有字母异位词
给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
说明:
- 字母异位词指字母相同,但排列不同的字符串。
- 不考虑答案输出的顺序。
示例 1:
输入:
s: "cbaebabacd" p: "abc"
输出:
[0, 6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
示例 2:
输入:
s: "abab" p: "ab"
输出:
[0, 1, 2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
sort(p.begin(),p.end());
vector<int> res;
for(int i=0;i<s.size();++i){
string tmp(s,i,p.size());
sort(tmp.begin(),tmp.end());
if(tmp == p)
{
res.push_back(i);
}
}
return res;
}
};
结果:
超时了!!暴力搜索看来没戏了,看了网上大神的解释,这种求子序列的题目一般都用sliding window进行。可以用两个变量left和right代表滑动串口的左右边界。于是就有以下解法:
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
if(s.empty()||s.size()<p.size())
return res;
int left = 0;
int right = p.size() - 1 ;
int a[26]={0};
int b[26]={0};
for(int i=0;i<p.size();i++){
a[(int)s[i]-'a']++;
b[(int)p[i]-'a']++;
}
while(right<s.size()){
int i=0;
for(;i<26;++i){
if(a[i]!=b[i])
break;
}
if(i==26)
res.push_back(left);
if(right+1 == s.size())
return res;
a[(int)s[left]-'a']--;
right++;
left++;
a[(int)s[right]-'a']++;
}
return res;
}
};
【反思】
所以回过头来,242题的复杂度有点高了,虽然这种做法很容易想到。我用hash的方法再实现了一下:
class Solution {
public:
bool isAnagram(string s, string t) {
map<char,int> a;
map<char,int> b;
for(auto c : s){
a[c]++;
}
for(auto c : t){
b[c]++;
}
return a==b;
}
};
242这道题比较特殊,都是小写字母,也可以直接用数组:
class Solution {
public:
bool isAnagram(string s, string t) {
int a[26]={};
int b[26]={};
for(auto c : s){
a[c-'a']++;
}
for(auto c : t){
b[c-'a']++;
}
for(int i=0;i<26;++i){
if(a[i]!=b[i])
return false;
}
return true;
}
};