242.有效的字母异位词
https://leetcode.cn/problems/valid-anagram/description/
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size()!=t.size())
return false;
int hash[26] = {0};
for(int i = 0; i < s.size(); i++)
{
hash[s[i] - 'a']++;
}
for(int i = 0; i < s.size(); i++)
{
hash[t[i] - 'a']--;
}
for(int i = 0; i < 26; i++)
{
if(hash[i]!=0)
return false;
}
return true;
}
};
349. 两个数组的交集
https://leetcode.cn/problems/intersection-of-two-arrays/description/
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> res;
unordered_set<int> nums(nums1.begin(),nums1.end());//把nums1全添加进来
for(int num : nums2) //遍历nums2数组
{
//nums2的元素在nums1里(也就是nums)出现过
if(nums.find(num) != nums.end())
res.insert(num);
}
return vector<int> (res.begin(),res.end());
}
};
383. 赎金信
https://leetcode.cn/problems/ransom-note/
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int len1 = ransomNote.size();
int len2 = magazine.size();
if(len1 > len2)
return false;
int hash[26] = {0};
for(int i = 0; i < len2; i++)
{
hash[magazine[i]-'a']++;
}
for(int i = 0; i < len1; i++)
{
hash[ransomNote[i]-'a']--;
}
for(int i = 0; i < 26; i++)
{
if(hash[i] < 0)
return false;
}
return true;
}
};
49.字母异位词分组
https://leetcode.cn/problems/group-anagrams/description/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
//对所有的string排序,比如bac cba cab 排完序后都是abc, 于是可以用map, abc就是索引, value值就是bac cba cab
unordered_map<string,vector<string>> mp;
for(string s : strs) //表示遍历strs的所有string, 这个str是入参
{
string cur = s; //用于记录cur,因为排序完之后就变了
sort(s.begin(),s.end()); //bac->abc
mp[s].push_back(cur);
}
vector<vector<string>> res;
for(auto vs : mp)//一次推入一个vector<string>
res.push_back(vs.second);
return res;
}
};
438.找到字符串中的所有字母异位词
https://leetcode.cn/problems/find-all-anagrams-in-a-string/description/
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
int m = p.size();
if(m > s.size())return {};
vector<int> res;
vector<int> hashs(26),hashp(26);
for(int i = 0; i < m; i++)
{
hashp[p[i]-'a']++;
hashs[s[i]-'a']++;
}
//此刻的hashp[]就是记录了abc有一个a 一个b 一个c
if(hashp == hashs)
res.push_back(0);
for(int i = m; i < s.size(); i++)
{
//滑动窗口,右边的加进来,左边的滑出去
hashs[s[i]-'a']++;
hashs[s[i-m]-'a']--;
if(hashp == hashs)
res.push_back(i-m+1);
}
return res;
}
};
349.两个数组的交集
https://leetcode.cn/problems/intersection-of-two-arrays/
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> res;
unordered_set<int> nums(nums1.begin(),nums1.end());//把nums1全添加进来
for(int num : nums2) //遍历nums2数组
{
//nums2的元素在nums1里(也就是nums)出现过
if(nums.find(num) != nums.end())
res.insert(num);
}
return vector<int> (res.begin(),res.end());
}
};
标签:return,string,int,res,代码,随想录,++,vector,哈希
From: https://www.cnblogs.com/xsl-blogs/p/17852381.html