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
Analysis
统计magazine
中各小写字母出现的次数,然后供ransomNote
使用,若发现某字母不足,则返回false
;函数未在循环中途return
,则说明为true
。
Code
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int maga[26] = {0};
for (char c : magazine)
maga[c- 97]++;
for (char c : ransomNote)
if (--maga[c - 97] < 0)
return false;
return true;
}
};
Appendix
- Link: https://leetcode.com/problems/ransom-note/
- Run Time: 19ms, beats 97.57%