383. 赎金信

题目来源:383. 赎金信

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false

(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine) {
  let noteMap = new Map();
  for(let note of ransomNote){
    noteMap.set(note, (noteMap.get(note) || 0)+1);
  }
  for(let ma of magazine){
    if(noteMap.get(ma) > 0){
      noteMap.set(ma, noteMap.get(ma) - 1);
    }    
  }
  let res = Array.from(noteMap.values()).filter((v)=>v!=0);
  return res.length ? false:true;
};

示例 1:

输入:ransomNote = "a", magazine = "b"
输出:false

示例 2:

输入:ransomNote = "aa", magazine = "ab"
输出:false

示例 3:

输入:ransomNote = "aa", magazine = "aab"
输出:true

 Python3

import collections
from typing import Collection


class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
      ra = collections.Counter(ransomNote)
      for c in magazine:
        if(ra.get(c)):
          ra[c] = ra.get(c) - 1
      
      return sum(ra.values()) == 0

if __name__ == '__main__':
  so = Solution()

  ransomNote , magazine = "a", "b"
  print(ransomNote , magazine, so.canConstruct(ransomNote , magazine))
  ransomNote , magazine = "aa", "ab"
  print(ransomNote , magazine, so.canConstruct(ransomNote , magazine))
  ransomNote , magazine = "aa", "aab"
  print(ransomNote , magazine, so.canConstruct(ransomNote , magazine))

 

提示:

  • 你可以假设两个字符串均只含有小写字母。
posted @ 2021-07-11 11:00  尖子  阅读(37)  评论(0编辑  收藏  举报