Skip to content

[LeetCode] 383. 赎金信 #92

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Sep 14, 2019 · 0 comments
Open

[LeetCode] 383. 赎金信 #92

Animenzzzz opened this issue Sep 14, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。

(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)

注意:

你可以假设两个字符串均只含有小写字母。

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

解题思路:使用哈希表记录字符与出现次数的映射,然后遍历ransomNote来和map进行比较

C++解题:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char,int> map;
        for(char cc:magazine) map[cc]++;
        for(char cc:ransomNote){
            if(!map[cc]) return false;
            else map[cc]--;
        }
        return true;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant