LeetCode——383. Ransom Letter

Title description:

Given a ransom letter (ransom) string and a magazine (magazine) string, determine whether the first string ransom can be composed of the characters in the second string magazines. If it can be formed, return true; otherwise, return false.
(Title description: In order not to expose the handwriting of the ransom letter, search for the required letters from the magazine and form words to express the meaning. Each character in the magazine string can only be used once in the ransom letter string.)

note:

  • You can assume that both strings contain only lowercase letters.
  • canConstruct(“a”, “b”) -> false
  • canConstruct(“aa”, “ab”) -> false
  • canConstruct(“aa”, “aab”) -> true

code show as below:

class Solution {
    
    
    public boolean canConstruct(String ransomNote, String magazine) {
    
    
        char[] ch1 = ransomNote.toCharArray();
        char[] ch2 = magazine.toCharArray();
        int m = ransomNote.length();
        int n = magazine.length();
        boolean flag = true;
        if (m > n) {
    
    
            return false;
        }
        HashMap<Character, Integer> map1 = new HashMap<>();
        HashMap<Character, Integer> map2 = new HashMap<>();
        for (int i = 0; i < m; i++) {
    
    
            map1.put(ch1[i], map1.getOrDefault(ch1[i], 0) + 1);
        }
        for (int j = 0; j < n; j++) {
    
    
            map2.put(ch2[j], map2.getOrDefault(ch2[j], 0) + 1);
        }
        for (var entry : map1.entrySet()) {
    
    
            if (map2.containsKey(entry.getKey()) && map2.get(entry.getKey()) >= (entry.getValue())) {
    
    
                flag = true;
            } else {
    
    
                flag = false;
                break;
            }
        }
        return flag;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114271817