您的位置:首页 > 其它

383. Ransom Note

2016-10-08 21:21 337 查看
原题链接:https://leetcode.com/problems/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.

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


题意:

给你两个字符串1和2,要去你判断能否用字符串2里面的字母组成字符串1,要求字符串2里面的字母一个只能用一次,能则return true 反之return false,给的字母都是小写字母。

思路:

用一个int数组保存26个小写字母在字符串2的出现次数,然后开始遍历字符串1,然后每次遇到一个字母,判断一次“库存”,不够,择return false,够则库存-1;遍历完成后,发现都够,则return true。

AC代码

class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int b[26]={0};
for(char s:magazine){
b[s-'a']++;
}
for(char s:ransomNote){
if(b[s-'a']==0) return false;
b[s-'a']--;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息