-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #454 from namita0210/Day-19-Q3
Day 19 Q3
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
Day-19/q3-Letter Combinations of a Phone Number/namita0210_java.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import java.util.ArrayList; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
|
||
public class namita0210_java { | ||
|
||
public static List<String> letterCombinations(String digits) { | ||
List<String> result = new ArrayList<>(); | ||
if (digits == null || digits.length() == 0) { | ||
return result; | ||
} | ||
|
||
Map<Character, String> digitToLetters = new HashMap<>(); | ||
digitToLetters.put('2', "abc"); | ||
digitToLetters.put('3', "def"); | ||
digitToLetters.put('4', "ghi"); | ||
digitToLetters.put('5', "jkl"); | ||
digitToLetters.put('6', "mno"); | ||
digitToLetters.put('7', "pqrs"); | ||
digitToLetters.put('8', "tuv"); | ||
digitToLetters.put('9', "wxyz"); | ||
|
||
generateCombinations(result, digits, digitToLetters, "", 0); | ||
|
||
return result; | ||
} | ||
|
||
private static void generateCombinations(List<String> result, String digits, Map<Character, String> digitToLetters, String current, int index) { | ||
if (index == digits.length()) { | ||
result.add(current); | ||
return; | ||
} | ||
|
||
char digit = digits.charAt(index); | ||
String letters = digitToLetters.get(digit); | ||
|
||
for (char letter : letters.toCharArray()) { | ||
generateCombinations(result, digits, digitToLetters, current + letter, index + 1); | ||
} | ||
} | ||
|
||
|
||
} |