In the Leetcode Letter Combinations of a Phone Number problem solution in Java programming 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.
Leetcode Letter Combinations of a Phone Number problem solution in Java programming
class Solution {
public List<String> letterCombinations(String digits) {
if (!(digits.contains("0") || digits.contains("1")) && !digits.isEmpty())
permutation("", digits);
return returnList;
}
ArrayList<String> returnList = new ArrayList<String>();
public String keypad(String digit){
switch(digit){
case "2": return "abc";
case "3": return "def";
case "4": return "ghi";
case "5": return "jkl";
case "6": return "mno";
case "7": return "pqrs";
case "8": return "tuv";
case "9": return "wxyz";
default : return "?";
}
}
public void permutation(String inputString, String remainingDigits){
if(remainingDigits.isEmpty())
returnList.add(inputString);
else{
String digit = remainingDigits.substring(0, 1);
String letters = keypad(digit);
for(int i = 0; i < letters.length(); i++){
String letter = keypad(digit).substring(i, i + 1);
permutation(inputString + letter, remainingDigits.substring(1));
}
}
}
}
Also read,
- Leetcode Letter Combinations of a Phone Number problem solution in C++
- Leetcode Letter Combinations of a Phone Number problem solution in C
- Leetcode Letter Combinations of a Phone Number problem solution in Python
- Leetcode Letter Combinations of a Phone Number problem solution in C#