Popular Posts

Saturday, March 19, 2011

Permutations for digits represented by Phone Number

Given a telephone number print or produce all the possible telephone words or combinations of letters that can represent the given telephone number


public class WordsByPhoneNumberDigits {
public static void main(String[] args) {
String[] charsOnPhonedigits = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs",
"tuv", "wxyz" };
String num = "23045";
num = num.replace("0", "");
num = num.replace("1", "");
char[] target = new char[10];
int bound = 0;
decodeNumber(charsOnPhonedigits, num, target, bound);
}

private static void decodeNumber(String[] charsOnPhonedigits, String num,
char[] target, int bound) {

if (num.length() == 0) {// decoded the total string.no need of recursion
StringBuilder str = new StringBuilder();
for (int i = 0; i < bound; i++) {
str.append(target[i]);
}
System.out.println(str);
return;
} else {
int firstChar = Integer.parseInt(num.charAt(0) + "");
int charsForDigit = charsOnPhonedigits[firstChar].length();
String pattern = charsOnPhonedigits[firstChar];

for (int k = 0; k < charsForDigit; k++) {
target[bound] = pattern.charAt(k);
if (num.length() != 1)
decodeNumber(charsOnPhonedigits, num.substring(1), target,
bound + 1);
else
decodeNumber(charsOnPhonedigits, "", target, bound + 1);
}
}
}
}

No comments:

Post a Comment