首页 > 代码库 > leetcode_383 Ransom Note(String)

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)