1. You are given a string str. The string str will contains numbers only, where each number stands for a key pressed on a mobile phone.
2. The following list is the key to characters map :Input Format
0 -> .;
1 -> abc
2 -> def
3 -> ghi
4 -> jkl
5 -> mno
6 -> pqrs
7 -> tu
8 -> vwx
9 -> yz
3. Complete the body of getKPC function - without changing signature - to get the list of all words that could be produced by the keys in str.
Use sample input and output to take idea about output.
A string strOutput Format
Contents of the arraylist containing words as shown in sample output
Constraints
0 <= str.length <= 10
str contains numbers only
Sample Input
78
Sample Output
[tv, tw, tx, uv, uw, ux]
Solution:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
ArrayList<String> res = getKPC(str);
System.out.println(res);
}
static String code[] = {".;","abc","def","ghi","jkl","mno","pqrs","tu","vwx","yz"};
public static ArrayList<String> getKPC(String str) {
ArrayList<String> res = new ArrayList<>();
if(str.length() ==0){
res.add("");
return res;
}
char ch = str.charAt(0);
ArrayList<String> ires = getKPC(str.substring(1));
String strCode = code[ch - '0'];
for(int i=0;i<strCode.length();i++){
char c = strCode.charAt(i);
for(String s:ires)
res.add(c+s);
}
return res;
}
}
Comments
Post a Comment