Interview Questions

Given a finite number, find out all the possible strings........

Microsoft Interview Questions and Answers


(Continued from previous question...)

122. Given a finite number, find out all the possible strings........

Question:
Given a finite number, find out all the possible strings that can be generated by using encoding found on phones for eg 112 => bad,bac,aae...etc. ( since 1 = abc , 2 = def ..


maybe an answer:


2 = "abc"
3 = "def"
5 = "jkl"
6 = "mno"
7 = "pqrs"
8 = "tuv"
9 = "wxyz"

void Encode(int a[], int length, int count, char *c)
{
static string str[] ={"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
if(count == length)
{
for(int i = 0 ; i < length ; i++)
cout<<c[i];
cout<<endl;
return;
}
for(int i = 0; i < str[a[count]].length() ; i++)
{
c[count] = str[a[count]][i];
Encode(a, length, count+1, c);
}
}



maybe an answer2:


Consider using recursion to solve the problem:
{
string[] map = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

List<string> getEncodings(int[] num, int index)
{
List<string> result = new List<string>();
if (index == num.Length - 1)
{
foreach (char c in map[num[index]].ToCharArray())
result.Add(c.ToString());
}
else
{
foreach (char c in map[num[index]].ToCharArray())
{
foreach (string str in getEncodings(num, index + 1))
result.Add(c.ToString() + str);
}
}
return result;
}
}

(Continued on next question...)

Other Interview Questions