From a91eb7d3b39ed1c26f4d1e0bcf24f9dc96174425 Mon Sep 17 00:00:00 2001 From: Namita <46557775+namita0210@users.noreply.github.com> Date: Wed, 17 Jan 2024 18:58:06 +0000 Subject: [PATCH] Day 19 Q3 - add java code --- .../namita0210_java.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Day-19/q3-Letter Combinations of a Phone Number/namita0210_java.java diff --git a/Day-19/q3-Letter Combinations of a Phone Number/namita0210_java.java b/Day-19/q3-Letter Combinations of a Phone Number/namita0210_java.java new file mode 100644 index 00000000..3310dcb3 --- /dev/null +++ b/Day-19/q3-Letter Combinations of a Phone Number/namita0210_java.java @@ -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 letterCombinations(String digits) { + List result = new ArrayList<>(); + if (digits == null || digits.length() == 0) { + return result; + } + + Map 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 result, String digits, Map 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); + } + } + + +}