C++實現手機按鍵輸出所有可能的單詞
在這個問題中,我們給定一個數字,需要打印出使用老式手機鍵盤按鍵組合可以形成的所有單詞。
我們現在都很熟悉QWERTY鍵盤樣式。但在QWERTY鍵盤發明之前,按鍵電話配備的是12個按鍵的鍵盤,每個按鍵包含單詞和數字。例如,鍵盤上的數字6包含單詞“MNO”,可以透過點選一次、兩次或三次按鍵來輸入。
鍵盤看起來像這樣:
1 | 2 ABC | 3 DEF |
4 GHI | 5 JKL | 6 MNO |
7 PQRS | 8 TUV | 9 WXYZ |
* | 0 | # |
在這些按鍵中也包含所有單詞,使用者可以使用它們進行輸入。因此,在這個問題中,我們將打印出使用給定的數字序列可以生成的所有可能的單詞。
讓我們來看一個例子,以便更好地理解這個問題:
Input: 687 Output: MTP, MTQ, MTR, MTR, MUP, MUQ, MUR, MUS, MVP, MVQ, MVR, MVR, NTP, NTQ, NTR, NTR, NUP, NUQ, NUR, NUS, NVP, NVQ, NVR, NVR, OTP, OTQ, OTR, OTR, OUP, OUQ, OUR, OUS, OVP, OVQ, OVR, OVR.
為了解決這個問題,讓我們看看上面例子中的模式。每個按鍵都有其關聯的字元,我們在輸入時必須使用它們。因此,對於每個數字,最多有4個選項(對於7和9)。為此,我們可以固定一個數字,然後使用該數字生成單詞。這可以使用遞迴來完成。
讓我們來看一個使用遞迴實現該概念的程式。
示例
#include <iostream> #include <string.h> using namespace std; const char keypad[10][5] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; void printWords(int number[], int curr_digit, char output[], int n){ int i; if (curr_digit == n){ cout<<output<<" "; return ; } for (i=0; i<strlen(keypad[number[curr_digit]]); i++){ output[curr_digit] = keypad[number[curr_digit]][i]; printWords(number, curr_digit+1, output, n); if (number[curr_digit] == 0 || number[curr_digit] == 1) return; } } int main(void){ int number[] = {6,8,7}; cout<<"The output character formed is : \n"; int n = sizeof(number)/sizeof(number[0]); char result[n+1]; result[n] ='\0'; printWords(number, 0, result, n); return 0; }
輸出
生成的輸出字元是:
mtp mtq mtr mts mup muq mur mus mvp mvq mvr mvs ntp ntq ntr nts nup nuq nur nus nvp nvq nvr nvs otp otq otr ots oup ouq our ous ovp ovq ovr ovs
廣告