电话按键单词问题(C/C++)

题目:请编写一个函数,它以一个7位数的电话号码为输入,把各种可能的“单词”,也就是能够用来代表给定号码的字母组合都打出来。由于电话上的“0” “1”按键上没有字母,所以你只需要把数字2-9转换成字母。

尝试用另一种方法解了一下这道题,效率为 O(3n)。

Code
/*
* 程序员面试攻略 (第二版)
* Programming Interviews Exposed (2nd Edition)
* P.104 电话按键单词
*
* by Fisher<aprilfishi@gmail.com>
* 2008-10-26
*/

#include
<iostream>
#include
<vector>

using namespace std;

char key_map[30] = { '0', '0', '0', // 0
'1', '1', '1', // 1
'A', 'B', 'C', // 2
'D', 'E', 'F', // 3
'G', 'H', 'I', // 4
'J', 'K', 'L', // 5
'M', 'N', 'O', // 6
'P', 'R', 'S', // 7
'T', 'U', 'V', // 8
'W', 'X', 'Y' // 9
};

// 接受电话号码的位数
const int DIGIT = 7;

char get_char_key(int telephone_key, int place);
void print_phone_words(int phone_number[]);
int pow(int x, int y);

int main()
{
int phone_number[] = {2,3,4,5,6,7,8};
print_phone_words(phone_number);

return 0;
}

void print_phone_words(int phone_number[])
{
int result_count = 1;

int place[DIGIT], p=1;
for (int i=0; i<DIGIT; i++)
{
if (phone_number[i] > 1)
{
place[i]
= p;
p
*= 3;
result_count
*= 3;
}
else
{
place[i]
= result_count;
}
}

vector
<vector<char> > result(result_count, vector<char>(DIGIT));

for (int i=0; i<DIGIT; i++)
{
p
=0;
for (int j=0; j<result_count; j++)
{
if ((j % place[i]) == 0)
p
++;
if (p > 3) p=1;
result[j][i]
= get_char_key(phone_number[i], p);
}
}

for (int i=0; i<result_count; i++)
{
cout
<< i << ": ";
for (int j=0; j<DIGIT; j++)
cout
<< result[i][j];
cout
<< "\t";

if (i % 4 == 0)
cout
<< endl;
}

cout
<< endl << endl;
for (int i=0; i<DIGIT; i++)
cout
<< "place[" << i << "] = " << place[i] << ";" << endl;
cout
<< endl;

cout
<< "result_count = " << result_count << endl;
}

inline
char get_char_key(int telephone_key, int place)
{
return key_map[3 * telephone_key + place - 1];
}

inline
int pow(int x, int y)
{
int s = x;

if (y==0)
return 1;

if (y==1)
return s;

for (int i=2; i<=y; i++)
s
*= x;

//printf("pow(%d, %d) = %d\r\n", x, y, s);
return s;
}

 

错误之处请指出,谢谢。

posted on 2008-10-27 21:10  Fisher.W  阅读(709)  评论(2)    收藏  举报