Created
May 18, 2023 12:04
-
-
Save jessejputnam/ce87697884e8d07f3de23b10559b1804 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
class Solution { | |
public List<String> letterCombinations(String digits) { | |
ArrayList<String> output = new ArrayList<>(); | |
String[] arr = getLettersArr(digits); | |
if (digits.isEmpty()) return output; | |
recur(arr, "", output); | |
return output; | |
} | |
private void recur(String[] arr, String cur, ArrayList<String> output) { | |
if (arr.length < 1) { output.add(cur); return; } | |
for (int i = 0; i < arr[0].length(); i++) { | |
recur(shiftArr(arr), cur += arr[0].charAt(i), output); | |
cur = cur.substring(0, cur.length() - 1); | |
} | |
} | |
private String[] shiftArr(String[] arr) { | |
String[] newArr = new String[arr.length - 1]; | |
for (int i = 1; i < arr.length; i++) newArr[i - 1] = arr[i]; | |
return newArr; | |
} | |
// Convert numbers to String of letter options | |
private String[] getLettersArr(String digits) { | |
String[] letters = new String[digits.length()]; | |
for (int i = 0; i < letters.length; i++) letters[i] = getDigitLetters(digits.charAt(i)); | |
return letters; | |
} | |
private String getDigitLetters(char num) { | |
if (num == '2') return "abc"; | |
if (num == '3') return "def"; | |
if (num == '4') return "ghi"; | |
if (num == '5') return "jkl"; | |
if (num == '6') return "mno"; | |
if (num == '7') return "pqrs"; | |
if (num == '8') return "tuv"; | |
if (num == '9') return "wxyz"; | |
return ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment