您的位置:首页 > 其它

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

2016-08-16 12:03 399 查看

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string leetcode hash