Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, August 3, 2017

Print all possible string formed from keys


Like old phone , alphabets were assigned to a number , print all possible string from those number'


Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
// static in=5;
    static String hashTable[] = {"", "", "abc", "def", "ghi", "jkl","mno", "pqrs", "tuv", "wxyz"};
public static void show(int arr[],StringBuffer Output,int cur,int n)
{
   if(cur>=n)
   {
       System.out.print(Output+" ");
       return;}
   else
   {
// loop of key 1 with all alphabets recursively
       for(int i=0;i<hashTable[arr[cur]].length();i++)
       {
           if(Output.length()>cur)
           Output.setCharAt(cur,hashTable[arr[cur]].charAt(i));
           else
           Output.append(hashTable[arr[cur]].charAt(i));
           show(arr,Output,cur+1,n);// go for next key 
       }
   }
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
   int n=ab.nextInt();
   int arr[]=new int[n];
   for(int i=0;i<n;i++)
   arr[i]=ab.nextInt();
   StringBuffer g=new StringBuffer();
   show(arr,g,0,n);
   System.out.println();
}
}
}

0 Comments:

Post a Comment

Stats