- 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;
- }
- };
- class Solution {
- public:
- bool isIsomorphic(string s, string t) {
- unordered_map<char, char> mp, mp2;
- for (int i=0; i
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;
- }
- };
- class Solution {
- public:
- bool wordPattern(string pattern, string s) {
- vector
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
wordSet; -
- for(int i=0; i
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.要先判断两个大小是否一样
- 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;
- }
- };
- 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
> groupAnagrams(vector& strs) { - unordered_map
> codeToGroup; - for(string s:strs){
- string code = encode(s);
- codeToGroup[code].push_back(s);
- }
-
- vector
> res; - for(auto group:codeToGroup){
- res.push_back(group.second);
- }
-
- return res;
- }
- };
也可以直接用sort
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- unordered_map<int, int> record;
- for(int i=0; i
size(); i++){ - int need = target-nums[i];
- if(record.count(need)){
- return {record[need], i};
- }
- record.emplace(nums[i], i);
- }
-
- return {};
- }
-
- };
- 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);
-
- }
- }
- };
- class Solution {
- public:
- bool containsNearbyDuplicate(vector<int>& nums, int k) {
- unordered_map<int, int> record;
- for(int i=0; i
size(); i++){ - if(record.count(nums[i])){
- int dif = i-record[nums[i]];
- if(dif <= k) return true;
-
- }
- record[nums[i]] = i;
- }
- return false;
- }
- };