2
头图

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.)

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/ransom-note/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Traverse the string
First declare a Map as charCount to record the number of occurrences of each character in ransomNote, key as the character that appears, value as the number of occurrences of repeated characters, then traverse ransomNote to initialize the number of character occurrences in ransomNote; then traverse each character in the magazine , Subtract the characters that still exist in the Map. After the final traversal is completed, if the charCount is empty, it means that the string ransom can be composed of the characters in the second string magazines, return true; otherwise, return false.
import java.util.HashMap;
import java.util.Map;

public class LeetCode_383 {
    public static boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> charCount = new HashMap<>();
        // 初始化 ransomNote 的字符出现次数
        for (char c : ransomNote.toCharArray()) {
            if (charCount.containsKey(c)) {
                charCount.put(c, charCount.get(c) + 1);
            } else {
                charCount.put(c, 1);
            }
        }
        // 判断 magazine 中是否有字符可以组成 ransomNote
        for (char c : magazine.toCharArray()) {
            if (charCount.containsKey(c)) {
                if (charCount.get(c) > 1) {
                    charCount.put(c, charCount.get(c) - 1);
                } else {
                    charCount.remove(c);
                }
            }
        }
        if (charCount.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(canConstruct("aa", "aab"));
    }
}
[Daily Message] not afraid of the word "difficult", you are afraid of the word "lazy".

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!