Skip to content

17. 电话号码的字母组合

17. 电话号码的字母组合

代码

javascript
// 17. 电话号码的字母组合:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/
// 输入:digits = "23"
// 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

export function letterCombinations (digits) {
  if (!digits.length) return []
  const numberObj = {
    2: ['a', 'b', 'c'],
    3: ['d', 'e', 'f'],
    4: ['g', 'h', 'i'],
    5: ['j', 'k', 'l'],
    6: ['m', 'n', 'o'],
    7: ['p', 'q', 'r', 's'],
    8: ['t', 'u', 'v'],
    9: ['w', 'x', 'y', 'z']
  }
  if (digits.length === 1) return numberObj[digits]
  const res = []
  const length = digits.length
  addString(0, '')

  function addString(start, resStr) {
    if (resStr.length === length) {
      res.push(resStr)
      return
    }
    const arr = numberObj[digits[start]]
    for (let i = 0; i < arr.length; i++) {
      addString(start + 1, resStr + arr[i])
    }
  }
  return res
}
typescript
// 17. 电话号码的字母组合:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/
// 输入:digits = "23"
// 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

export function letterCombinations(digits: string): string[] {
  if (!digits.length) return []
  const numberObj: { [key: string]: string[] } = {
    2: ['a', 'b', 'c'],
    3: ['d', 'e', 'f'],
    4: ['g', 'h', 'i'],
    5: ['j', 'k', 'l'],
    6: ['m', 'n', 'o'],
    7: ['p', 'q', 'r', 's'],
    8: ['t', 'u', 'v'],
    9: ['w', 'x', 'y', 'z']
  }
  if (digits.length === 1) return numberObj[digits]
  const res: string[] = []
  const length = digits.length
  addString(0, '')

  function addString(start: number, resStr: string) {
    if (resStr.length === length) {
      res.push(resStr)
      return
    }
    const arr = numberObj[digits[start]]
    for (let i = 0; i < arr.length; i++) {
      addString(start + 1, resStr + arr[i])
    }
  }
  return res
}

测试代码

ts
import { expect, test } from 'vitest'
import { letterCombinations } from './typescript.ts'
import { letterCombinations as letterCombinationsJs } from './javascript.js'

test(`letterCombinations('23')`, () => {
  expect(letterCombinations('23')).toEqual(["ad","ae","af","bd","be","bf","cd","ce","cf"])
})

test(`letterCombinationsJs('23')`, () => {
  expect(letterCombinationsJs('23')).toEqual(["ad","ae","af","bd","be","bf","cd","ce","cf"])
})