Leetcode (OK)242 1 219 (思路)383 202 (*)205 290 49

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 mp, mp2;
        for (int i=0; i

290. Word Pattern(*)

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 patternToWord;
        unordered_set wordSet;

        for(int i=0; i

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 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

1. Two Sum

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        unordered_map record;
        for(int i=0; i

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 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& nums, int k) {
        unordered_map record;
        for(int i=0; i

你可能感兴趣的:(leetcode,算法,职场和发展)