您的位置:首页 > 其它

383. Ransom Note(map容器)

2018-02-26 17:50 295 查看

题目

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

题意

判断字符串ransomNote中的元素是否是由magazine里的元素构成的。

题解

C++代码

class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
map<char, int>m;
for(int i=0; i<magazine.length(); i++)
{
m[magazine[i]]++;
}
for(int i=0; i<ransomNote.length(); i++)
{
if(m[ransomNote[i]]==0)
return false;
m[ransomNote[i]]--;
}
return true;
}
};


python代码

class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
ransomNote = list(ransomNote)
magazine = list(magazine)
for i in range(0, len(ransomNote)):
if ransomNote[i] in magazine:
magazine.remove(ransomNote[i])
else:
return False
return True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: