1. 程式人生 > 其它 >【LeetCode】383. Ransom Note 贖金信(Easy)(JAVA)

【LeetCode】383. Ransom Note 贖金信(Easy)(JAVA)

技術標籤:Leetcode字串leetcodejava演算法面試

【LeetCode】383. Ransom Note 贖金信(Easy)(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.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

Constraints:

  • You may assume that both strings contain only lowercase letters.

題目大意

給定一個贖金信 (ransom) 字串和一個雜誌(magazine)字串,判斷第一個字串 ransom 能不能由第二個字串 magazines 裡面的字元構成。如果可以構成,返回 true ;否則返回 false。

(題目說明:為了不暴露贖金信字跡,要從雜誌上搜索各個需要的字母,組成單詞來表達意思。雜誌字串中的每個字元只能在贖金信字串中使用一次。)

注意:

  • 你可以假設兩個字串均只含有小寫字母。

解題方法

  1. 就是判斷 ransomNote 的字元是否在 magazine 都有,而且 magazine 中字元不能重複使用
  2. 因為這一題的字串只包含小寫字母所以用一個長度 26 的一維陣列存字母出現的次數; ransomNote 字母出現 -1, magazine字母出現 +1
  3. 最後判斷下字母出現次數是否大於等於 0 即可
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote.length() > magazine.length()) return false;
        int[] count = new int[26];
        for (int i = 0; i < magazine.length(); i++) {
            count[magazine.charAt(i) - 'a']++;
            if (i < ransomNote.length()) count[ransomNote.charAt(i) - 'a']--;
        }
        for (int i = 0; i < count.length; i++) {
            if (count[i] < 0) return false;
        }
        return true;
    }
}

執行耗時:3 ms,擊敗了62.61% 的Java使用者
記憶體消耗:38.7 MB,擊敗了70.26% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新