LeetCode383 Ransom Note


描述

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.

样例

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

思路

给两个字符串,在第二个串中每个字母只能使用一次的情况下,问能否构造得到第一个串。

首先遍历第二个串,得到每个字母的个数,然后再遍历第一个串,看对应字母的个数是否足够即可。

代码

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int cnt[26] = {0};
for (auto& ch: magazine) cnt[ch-'a']++;
for (auto& ch: ransomNote) {
if (--cnt[ch-'a'] < 0) return false;
}
return true;
}
};