可用于拨号的所有字符串组合

给定一个号码,打印所有可能的字符串组合,这些字符串可用于在具有以下规格的手机中拨打给定号码。

null

在给定的电话中,我们可以拨打, 2使用A、B或C, 3使用D或E或F, ………………. 8使用T或U或V, 9使用W或X或Y或Z, 1只使用1 0使用0。

例如,如果23是给定的电话号码,程序应该打印广告、AE、AF、BD、BE、BF、CD、CE、CF

其想法是在哈希映射中存储数字到字符的映射。地图存储了所有可以用来拨号的字符。我们为当前数字放置每个可能的字符,并为剩余数字重现。下面是这个想法的Java实现。

// Java program to print all possible key strings
// that can be used to dial a phone number.
import java.util.HashMap;
class ConvertToString
{
// A Recursive function to print all combinations
// that can be used to dial a given number.
// phNo ==> Given Phone Number
// i    ==> Current digit of phNo to be processed
// hm   ==> Stores characters that can be used to
//          to dial a digit.
// str  ==> Current output string
static void printStrings(String phNo, int i,
HashMap<Character, String> hm,
StringBuilder str)
{
// If all digits are processed, print output
// string
if (i == phNo.length())
{
System.out.print(str + " " );
return ;
}
// Get current digit of phNo, and recur for all
// characters that can be used to dial it.
String s = hm.get(phNo.charAt(i));
for ( int j = 0; j < s.length(); j++)
{
str.append(s.charAt(j));
printStrings(phNo, i+1, hm, str);
str.deleteCharAt(str.length()-1);
}
}
// Prints all possible combinations of strings that
// can be used to dial c[].
static void printStringForNumber(String phNo)
{
// Create a HashMap
HashMap<Character, String> hm =
new HashMap<Character, String>();
// For every digit, store characters that can
// be used to dial it.
hm.put( '2' , "ABC" );
hm.put( '3' , "DEF" );
hm.put( '4' , "GHI" );
hm.put( '5' , "JKL" );
hm.put( '6' , "MNO" );
hm.put( '7' , "PQRS" );
hm.put( '8' , "TUV" );
hm.put( '9' , "WXYZ" );
hm.put( '1' , "1" );
hm.put( '0' , "0" );
// Create a string to store a particular output
// string
StringBuilder str = new StringBuilder();
// Call recursive function
printStrings(phNo, 0, hm, str);
}
// Driver code to test above methods
public static void main(String args[])
{
// Prints
printStringForNumber( "23" );
}
}


输出:

AD AE AF BD BE BF CD CE CF 

本文由 法尔根 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享