您的位置:首页 > 其它

LeetCode-383. Ransom Note

2017-02-23 17:19 399 查看
问题:https://leetcode.com/problems/ransom-note/?tab=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. 给定一个字符串ransom和一个字符串magazine,判定是否所有ransom中的字符都出现在了magazine里。

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

分析:统计多字母那个字符串中各个字母出现的次数,然后再用ransomNote中字母出现了,就减去1,如果不能包含所有的话,会减到0。

C++代码:

class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int lr=ransomNote.length();
int lm=magazine.length();
vector<int> box(128,0);
if(lr==0) return true;
if(lr>lm) return false;
for(char m:magazine){
box[m]++;
}
for(char r:ransomNote){
if(box[r]==0) return false;
box[r]--;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string 函数 leetcode