题目地址:https://leetcode.com/problems/ransom-note/open in new window

  • Difficulty: Easy

题目描述

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:

Youmay assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

题目大意

判断ransom能否由magazines的字符构成。

解题方法

Java解法

理解题意很关键,这个是说从magazine中取出几个元素排列组合能够摆成ransomNote。

参考Find the Difference的题目,做个有26个位置的数组,保存字符出现的次数,最后统计一下即可。

其中一个字符串的元素使位置元素++,另外个字符串使字符串--;

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if(ransomNote.length() > magazine.length())
            return false;
        int []chars= new int[26];
        for(int i=0; i< magazine.length(); i++){
            chars[magazine.charAt(i)- 'a']++;
        }
        for(int i=0; i< ransomNote.length(); i++){
            chars[ransomNote.charAt(i)- 'a']--;
            if(chars[ransomNote.charAt(i)- 'a'] < 0){
                return false;
            }
        }
        return true;
    }
}

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

AC:18 ms

Python解法

直接Counter,然后判断前者的每个字符出现次数都小于后者即可。

class Solution:
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        rcount = collections.Counter(ransomNote)
        mcount = collections.Counter(magazine)
        for r, c in rcount.items():
            if c > mcount[r]:
                return False
        return True

1 2 3 4 5 6 7 8 9 10 11 12 13

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发