前记

360三面已过,后接能力测评,一切都没感觉有何异样, 然而并没有收到offer, 躺在了所谓的offer池(备胎池)中, 甚是伤感, 只能说他皮任他皮,我刷我的题~

Description

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

My solution

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int mag[256] = {0};
        for (int i = 0; i < magazine.size(); i++) mag[magazine[i]]++;
        for (int i = 0; i < ransomNote.size(); i++) mag[ransomNote[i]]--;
        for(int i=0;i<256;i++) if(mag[i]<0) return false;
        return true;
    }
};

基本思路是没有问题的, 可优化主要有两点:

  • 内存浪费(实际26个字母用不到这么大空间)
  • 第三个for可以归入第二个for里面

Discuss

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char, int> map(26);
        for (int i = 0; i < magazine.size(); ++i)
            ++map[magazine[i]];
        for (int j = 0; j < ransomNote.size(); ++j)
            if (--map[ransomNote[j]] < 0)
                return false;
        return true;
    }
};

或者:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        vector<int> vec(26, 0);
        for (int i = 0; i < magazine.size(); ++i)
            ++vec[magazine[i] - 'a'];
        for (int j = 0; j < ransomNote.size(); ++j)
            if (--vec[ransomNote[j] - 'a'] < 0)
                return false;
        return true;
    }
};

自己重写如下, 学会用map:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char,int> mp;
        for(int i=0;i<magazine.size();++i) mp[magazine[i]]++;
        for(int i=0;i<ransomNote.size();++i) if(--mp[ransomNote[i]]<0) return false;
        return true;
    }
};

注意 unordered_map<char,int> mp; 可以直接++

类似的:

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, int> mp;
        for (int i = 0; i < s.size(); ++i) ++mp[s[i]];
        for (int i = 0; i < s.size(); ++i) if (mp[s[i]] == 1) return i;
        return -1;
    }
};
// unordered_map
class Solution {
public:
    char findTheDifference(string s, string t) {
        unordered_map<char,int> mp;
        for(int i=0;i<s.size();++i) ++mp[s[i]];
        for(int i=0;i<t.size();++i) if(--mp[t[i]]<0) return t[i];
        return 0;
    }
};

// bit trick
class Solution {
public:
    char findTheDifference(string s, string t) {
        char res=0;
        for(int i=0;i<s.size();++i) res^=s[i];
        for(int i=0;i<t.size();++i) res^=t[i];
        return res;
    }
};

Reference


xufeng
8 声望3 粉丝

有多少人工就有多少智能