383. Ransom Note

    xiaoxiao2026-01-09  10

    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 Subscribe to see which companies asked this question

    解题思路: 给定一个随机字符串,另外一个字符串是否包含这个字符串所有元素个数。建一个26个字母的数组,对随机字符串进行求统计,然后再对另外一个字符串求统计,如果没有出现负值表示true,出现负值表示false。

    class Solution { public: bool canConstruct(string ransomNote, string magazine) { vector<int> charcnt(26,0); for(int i = 0; i < ransomNote.size(); ++i) { charcnt[ransomNote[i]-'a'] --; } for(int i = 0; i < magazine.size(); ++i) { charcnt[magazine[i]-'a'] ++; } for(int i = 0; i < 26; ++i) { if(charcnt[i] < 0) { return false; } } return true; } };
    转载请注明原文地址: https://ju.6miu.com/read-1305815.html
    最新回复(0)