Leetcode - String - 383. Ransom Note(水题)

来源:互联网 发布:c语言标准库函数时间 编辑:程序博客网 时间:2024/06/07 15:24

1. Problem Description

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

 

给出两个字符串,判断第一个字符串能否由第二个字符串构成,每个字符只能使用一次,假设都是小写。

 

2. My solution(24ms)

class Solution {public:    bool canConstruct(string ransomNote, string magazine) {        int cnt[26];        for(int i=0;i<26;i++)   cnt[i]=0;        int lenr=ransomNote.length(),lenm=magazine.length();        for(int i=0;i<lenm;i++)        {           int tmp=magazine[i]-'a';            cnt[tmp]++;        }        for(int i=0;i<lenr;i++)        {            int tmp=ransomNote[i]-'a';            cnt[tmp]--;            if(cnt[tmp]<0)                return false;        }        return true;    }};


0 0