17. Letter Combinations of a Phone Number

  • Source : Link
  • Author : Han
  • Date : 2022-01-28

Problems

GiGiven a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png

Example 1:

1
2
3
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

1
2
3
Input: digits = ""
Output: []

Example 3:

1
2
3
Input: digits = "2"
Output: ["a","b","c"]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    fun letterCombinations(digits: String): List<String> {
        if (digits.isEmpty()) return emptyList()
        val digitMap = mapOf(
            "2" to listOf("a", "b", "c"),
            "3" to listOf("d", "e", "f"),
            "4" to listOf("g", "h", "i"),
            "5" to listOf("j", "k", "l"),
            "6" to listOf("m", "n", "o"),
            "7" to listOf("p", "q", "r", "s"),
            "8" to listOf("t", "u", "v"),
            "9" to listOf("w", "x", "y", "z")
        )
        return digits.mapNotNull { digitMap[it.toString()] }.reduce { arr, addArr ->
            arr.flatMap { i -> addArr.map { j -> i + j } }
        }
    }
}