[LeetCode] 383. Ransom Note

Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

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:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.

赎金条。

为了不在赎金信中暴露字迹,从杂志上搜索各个需要的字母,组成单词来表达意思。

给你一个赎金信 (ransomNote) 字符串和一个杂志(magazine)字符串,判断 ransomNote 能不能由 magazines 里面的字符构成。

如果可以构成,返回 true ;否则返回 false 。

magazine 中的每个字符只能在 ransomNote 中使用一次。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ransom-note
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

canConstruct 函数里面有两个参数,判断第一个字符串 ransomNote 里面所有的字母是不是在第二个字符串 magazine 里面都出现了。如果有重复的字母,需要判断出现的次数是否足够(如第二个例子a的数量不够,就return false)。

这题也是 counting sort 的思路做。这题跟[LeetCode] 242. Valid Anagram不同的地方在于 ransomNote 里面会包含 magazine 里面不存在的字符。思路是先用一个 hashmap 存所有在 magazine 中出现的字母及其次数;然后扫描 ransomnote 的时候判断是不是每个字母都在 hashmap 出现过并且出现过足够多次数。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean canConstruct(String ransomNote, String magazine) {
 3         int[] count = new int[26];
 4         for (int i = 0; i < magazine.length(); i++) {
 5             count[magazine.charAt(i) - 'a']++;
 6         }
 7         for (int i = 0; i < ransomNote.length(); i++) {
 8             if (--count[ransomNote.charAt(i) - 'a'] < 0) {
 9                 return false;
10             }
11         }
12         return true;
13     }
14 }

 

JavaScript实现

 1 /**
 2  * @param {string} ransomNote
 3  * @param {string} magazine
 4  * @return {boolean}
 5  */
 6 var canConstruct = function(ransomNote, magazine) {
 7     let map = {};
 8     for (let i = 0; i < magazine.length; i++) {
 9         let cur = magazine[i];
10         if (!map[cur]) {
11             map[cur] = 1;
12         } else {
13             map[cur]++;
14         }
15     }
16     for (let j = 0; j < ransomNote.length; j++) {
17         let cur = ransomNote[j];
18         if (!map[cur] || --map[cur] < 0) {
19             return false;
20         }
21     }
22     return true;
23 };

 

LeetCode 题目总结

posted @ 2019-10-10 06:46  CNoodle  阅读(277)  评论(0编辑  收藏  举报