leetcode_383 Ransom Note(String)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode_383 Ransom Note(String)相关的知识,希望对你有一定的参考价值。

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
给定两个字符串,判断前一个字符串能否由后一个字符串构成,后一个字符串中的字符只能使用一次。

solution1:定义一个长度为26的数组,对应26个字母

 java中默认整数数组自动赋值为0

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

solution2:hashmap

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> map= new HashMap<>();
        for (char c:magazine.toCharArray()){
            int count = magM.getOrDefault(c, 0)+1;
            map.put(c, count);
        }
        for (char c:ransomNote.toCharArray()){
            int count = map.getOrDefault(c,0)-1;
            if (count<0)
                return false;
            map.put(c, count);
        }
        return true;
    }
}

 





以上是关于leetcode_383 Ransom Note(String)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode_383 Ransom Note(String)

LeetCode 383. Ransom Note

LeetCode(383)Ransom Note

LeetCode 383 Ransom Note

LeetCode 383 Ransom Note

[LeetCode]383. Ransom Note 解题小结