Skip to content

Latest commit

 

History

History
46 lines (39 loc) · 1017 Bytes

383.赎金信.md

File metadata and controls

46 lines (39 loc) · 1017 Bytes

383.赎金信

/*
 * @lc app=leetcode.cn id=383 lang=typescript
 *
 * [383] 赎金信
 */

// @lc code=start
function canConstruct(ransomNote: string, magazine: string): boolean {}
// @lc code=end

解法 1

function canConstruct(ransomNote: string, magazine: string): boolean {
  if (ransomNote.length > magazine.length) return false

  const map = new Map<string, number>()
  for (const c of magazine) {
    map.set(c, (map.get(c) ?? 0) + 1)
  }
  for (const c of ransomNote) {
    if (!map.get(c)) return false
    map.set(c, map.get(c)! - 1)
  }
  return true
}

Case

test.each([
  { input: { ransomNote: 'a', magazine: 'b' }, output: false },
  { input: { ransomNote: 'aa', magazine: 'ab' }, output: false },
  { input: { ransomNote: 'aa', magazine: 'aab' }, output: true },
])(
  'input: ransomNote = $input.ransomNote, magazine = $input.magazine',
  ({ input: { ransomNote, magazine }, output }) => {
    expect(canConstruct(ransomNote, magazine)).toEqual(output)
  },
)