Skip to content

383、赎金信

js
;(function () {
  /**
     * 给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
     * 如果可以,返回 true ;否则返回 false 。
     * magazine 中的每个字符只能在 ransomNote 中使用一次。
     * @param {string} ransomNote
     * @param {string} magazine
     * @return {boolean}
     * 
     * 输入:ransomNote = "a", magazine = "b"
     * 输出:false
     * 
     * 输入:ransomNote = "aa", magazine = "ab"
     * 输出:false
     * 
     * 输入:ransomNote = "aa", magazine = "aab"
     * 输出:true
     * 
     * 提示:
        1 <= ransomNote.length, magazine.length <= 105
        ransomNote 和 magazine 由小写英文字母组成
     */
  var canConstruct = function (ransomNote: string, magazine: string): boolean {
    // 方法一:
    // let bool = true;
    // let len = ransomNote.length;
    // let lenM = magazine.length;
    // if (len > lenM) {
    //     return false
    // }
    // for (let i = 0; i < len; i++) {
    //     let index = magazine.indexOf(ransomNote[i]);
    //     // 如果有不存在的字符,则直接中断返回false
    //     if (index === -1) {
    //         bool = false;
    //         break;
    //     } else {
    //         magazine = magazine.replace(ransomNote[i], '')
    //     }
    // }
    // return bool

    // 方法二: 字符统计(官方方法)
    if (ransomNote.length > magazine.length) {
      return false
    }
    const cnt = new Array(26).fill(0)
    const aCharCode = 'a'.charCodeAt(0) // 97
    for (const c of magazine) {
      // 长字符串累加
      cnt[c.charCodeAt(0) - aCharCode]++
    }
    for (const c of ransomNote) {
      // 短字符串递减
      cnt[c.charCodeAt(0) - aCharCode]--
      // 如果同一个字符减到小于0,说明 长字符串 不包含 短字符串
      if (cnt[c.charCodeAt(0) - aCharCode] < 0) {
        return false
      }
    }
    return true

    // 方法三: substr  'stt'.substr(1) // tt
  }
  // let ransomNote = "aa", magazine = "aab";
  // let ransomNote = "aa", magazine = "ab";
  let ransomNote = 'bgx',
    magazine = 'efjbdfbdgfjhhaiigfhbaejahgfbbgbjagbddfgdiaigdadhcfcj' // true

  console.log(canConstruct(ransomNote, magazine))
})()