您的位置:首页 > 编程语言 > C语言/C++

LeetCode 383. Ransom Note

2017-04-04 08:16 323 查看

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%
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string leetcode cpp ransom