383. Ransom Note(想一下思路)
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int record[26]{0};
for(auto num:magazine){
record[num-'a']++;
}
for(auto note:ransomNote){
record[note-'a']--;
}
for(int i=0; i<26; i++){
if(record[i] < 0)
return false;
}
return true;
}
};
205. Isomorphic Strings(*)
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> mp, mp2;
for (int i=0; i<s.length(); ++i) {
if(mp[s[i]] && mp[s[i]] != t[i]) return false;
if(mp2[t[i]] && mp2[t[i]] != s[i]) return false;
mp[s[i]] = t[i];
mp2[t[i]] = s[i];
}
return true;
}
};
290. Word Pattern(*)
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string> words;
string sub_s;
for(auto val:s){
if(val == ' '){
words.push_back(sub_s);
sub_s = "";
}else{
sub_s.push_back(val);
}
}
words.push_back(sub_s);
if(pattern.size() != words.size()) return false;
unordered_map<char, string> patternToWord;
unordered_set<string> wordSet;
for(int i=0; i<pattern.size(); ++i){
string s = words[i];
char ch = pattern[i];
if(!patternToWord.count(ch)){
if(wordSet.count(s)) return false;
patternToWord[ch] = s;
}else{
if(patternToWord[ch] != s) return false;
}
wordSet.insert(s);
}
return true;
}
};
1.注意如何存储单词
2.要先判断两个大小是否一样
242. Valid Anagram
class Solution {
public:
bool isAnagram(string s, string t) {
int record[26]{0};
for(auto ch:s){
record[ch-'a']++;
}
for(auto ch:t){
record[ch-'a']--;
}
for(int i=0; i<26; i++){
if(record[i] != 0) return false;
}
return true;
}
};
49. Group Anagrams(*)
class Solution {
private:
string encode(string str){
vector<int> count{26, 0};
for(char ch:str){
count[ch-'a'] ++;
}
string code(count.begin(), count.end());
return code;
}
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> codeToGroup;
for(string s:strs){
string code = encode(s);
codeToGroup[code].push_back(s);
}
vector<vector<string>> res;
for(auto group:codeToGroup){
res.push_back(group.second);
}
return res;
}
};
也可以直接用sort
1. Two Sum
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> record;
for(int i=0; i<nums.size(); i++){
int need = target-nums[i];
if(record.count(need)){
return {record[need], i};
}
record.emplace(nums[i], i);
}
return {};
}
};
202. Happy Number(想一下思路)
class Solution {
private:
int getSum(int n){
int sum = 0;
while(n >= 1){
sum += (n%10) * (n%10);
n /= 10;
}
return sum;
}
public:
bool isHappy(int n) {
unordered_set<int> record;
while(1){
n= getSum(n);
if(n == 1) return true;
if(record.count(n)) return false;
record.insert(n);
}
}
};
219. Contains Duplicate II(OK)
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> record;
for(int i=0; i<nums.size(); i++){
if(record.count(nums[i])){
int dif = i-record[nums[i]];
if(dif <= k) return true;
}
record[nums[i]] = i;
}
return false;
}
};