描述
给你两个字符串:ransomNote
和 magazine
,判断 ransomNote
能不能由 magazine
里面的字符构成。
如果可以,返回 true
;否则返回 false
。
magazine
中的每个字符只能在 ransomNote
中使用一次。
思路
计算26字符出现次数的问题
代码
impl Solution {
pub fn can_construct(ransom_note: String, magazine: String) -> bool {
let baseChar = 'a';
let mut record = vec![0; 26];
for c in magazine.bytes() {
record[c as usize - baseChar as usize] += 1;
}
for c in ransom_note.bytes() {
record[c as usize - baseChar as usize] -= 1;
if (record[c as usize - baseChar as usize] < 0) {
return false;
}
}
true
}
}