目录
一、题目
1、题目描述
给你两个字符串:
ransomNote
和magazine
,判断ransomNote
能不能由magazine
里面的字符构成。如果可以,返回
true
;否则返回false
。
magazine
中的每个字符只能在ransomNote
中使用一次。
2、接口描述
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
}
};
3、原题链接
二、解题报告
1、思路分析
小写字母只有26个,先统计magazine的各个小写字母的个数,然后遍历ransomNote,对应的字符个数-1,如果出现-1后有字符数目小于0那么返回false
否则返回true
2、复杂度
时间复杂度:O(n) 空间复杂度:O(1)
(Python3代码由于用了Counter空间复杂度应该是O(C)的)
3、代码详解
C++代码
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int h1[26]{0};
for(auto x : magazine) h1[x - 'a']++;
for(auto x : ransomNote) if(--h1[x - 'a'] < 0) return false;
return true;
}
};
Python3代码
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
return Counter(ransomNote) <= Counter(magazine)