LeetCode 383. Ransom Note 原创Java参考解答

LeetCode 383. Ransom Note 原创Java参考解答

问题描述

https://leetcode.com/problems/ransom-note/

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

解题思路

题目是问字符串ransomNote是否是字符串magazine中的一部分。

首先,如果ransomNote字符串长度大于magazine的字符串长度,显然不是。

接着,用一个长度26的数组统计magazine中出现的字符次数。然后用数组中的数字与ransomNote中的字符一一相减的方法,比对ransomNote中是否存在任何字符的出现次数是超出了magazine中的出现次数。

参考代码

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

相关题目

LeetCode All in One 原创题目讲解汇总

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注