Letter Combinations of a Phone Number - LeetCode
Can you solve this real interview question? Letter Combinations of a Phone Number - Given 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 d
leetcode.com
Problem
Given 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 digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
- 0 <= digits.length <= 4
- digits[i] is a digit in the range ['2', '9'].
Solution
나의 풀이법
최종 소스코드
class Solution {
val answer = arrayListOf<String>()
val nums = arrayOf(
arrayOf(),
arrayOf(),
arrayOf("a", "b", "c"),
arrayOf("d", "e", "f"),
arrayOf("g", "h", "i"),
arrayOf("j", "k", "l"),
arrayOf("m", "n", "o"),
arrayOf("p", "q", "r", "s"),
arrayOf("t", "u", "v"),
arrayOf("w", "x", "y", "z"))
fun letterCombinations(digits: String): List<String> {
if (digits=="") return answer
makeWords(digits, 0, "")
return answer
}
private fun makeWords(digits: String, index: Int, s: String) {
val nextIndex = if (index == digits.length-1) -1 else index+1
nums[digits[index].toString().toInt()].forEach {
if (nextIndex == -1) answer.add("$s$it")
else makeWords(digits, nextIndex, "$s$it")
}
}
}
- 전역 변수 선언
- 각 번호에 맞는 string 값을 저장한 배열 nums를 전역변수로 선언합니다.
- 정답을 저장할 ArrayList를 전역 변수로 선언합니다.
- 단어를 조합하는 makeWords 함수
- 입력한 숫자값 digits, 현재 index, 그리고 조합한 문자 s를 입력받습니다.
- nums에서 digits[index]에 해당하는 값의 문자를 입력받은 문자 s 뒤에 붙입니다.
- 현재 index 값이 digits의 lastIndex와 동일하면 조합된 문자를 answer에 추가합니다.
- (재귀) 현재 index 값이 digits의 lastIndex보다 작으면 조합된 문자와 index+1을 다시 makeWords로 호출합니다.
- 재귀가 끝나면 완성된 answer 값을 리턴합니다.
Comment
좀 더 간결하게 풀고 싶었으나 한계였다…
접근 자체는 어렵지 않았다.
처음엔 숫자 순서대로 단어를 조합하는 것이 아닌 숫자 조차도 순서가 섞이는 줄 알았는데, 순서대로라는 걸 깨닫고 나서는 접근이 쉬워졌다.
'LeetCode > Kotlin | Medium' 카테고리의 다른 글
[LeetCode/Kotlin]Medium - 53. Maximum Subarray (0) | 2023.08.03 |
---|---|
[LeetCode/Kotlin]Medium - 200. Number of Islands (0) | 2023.08.03 |
[LeetCode/Kotlin]Medium - 926. Flip String to Monotone Increasing (0) | 2023.07.16 |
[LeetCode/Kotlin]Medium - 22. Generate Parentheses (0) | 2023.07.07 |
[LeetCode/Kotlin]Medium - 1027. Longest Arithmetic Subsequence (0) | 2023.06.30 |