关闭

LeetCode383. Ransom Note优雅解法(线性时间复杂度)

标签: C++Leetcodestring函数character
392人阅读 评论(0) 收藏 举报
分类:


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

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int pool[26] = {0};
        for (char c : magazine) {
            pool[c-'a']++;
        }
        for (char c : ransomNote) {
            if (pool[c-'a'] > 0) {
                pool[c-'a']--;
            } else {
                return false;
            }
        }
        return true;
    }
};



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人简介
    个人资料
    • 访问:736377次
    • 积分:7849
    • 等级:
    • 排名:第2752名
    • 原创:274篇
    • 转载:6篇
    • 译文:1篇
    • 评论:196条
    我的小站
    最新评论
    --
    我要啦免费统计