383. Ransom Note(map容器)

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/xunalove/article/details/79380087

题目

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

猜你喜欢

转载自blog.csdn.net/xunalove/article/details/79380087