一道摩尔电码翻译的题,用的模拟,还好数据量不大,如果数据量大了,得上map,或者字典树了。。
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int n;
string chara[40]={"12", "2111", "2121", "211", "1", "1121", "221", "1111", "11", "1222", "212", "1211", "22", "21", "222", "1221",
"2212", "121", "111", "2", "112", "1112", "122", "2112", "2122", "2211", /*符号*/ "1122"/*_*/, "2221",/*.*/ "1212",/*,*/ "2222"/*?*/};
int main()
{
while ( EOF != scanf("%d", &n) )
{
int q;
for (q=1; q<=n; q++)
{
int num[100];
char str[510];
string ch="";
scanf("%s", str);
int i, j, k= 0, p= 0, len;
for ( i = 0; str[i] != 0; i++ )
{
if ( 'A' <= str[i] && 'Z' >= str[i] )
{
num[i]= chara[str[i]-'A'].length();
ch+=chara[str[i]-'A'];
}
else if ( str[i] == '_' )
{
num[i]= chara[26].length();
ch+=chara[26];
}
else if ( str[i] == '.' )
{
num[i]= chara[27].length();
ch+=chara[27];
}
else if ( str[i] == ',' )
{
num[i]= chara[28].length();
ch+=chara[28];
}
else if ( str[i] == '?' )
{
num[i]= chara[29].length();
ch+=chara[29];
}
k++;
}
printf("%d: ", q);
for ( i= k-1; i >= 0; i--)
{
len= num[i];
string t;
for ( j= 0; j < len; j++)
t+=ch[j+p];
for ( j = 0; j < 30 && t != chara[j]; j++);
if ( 0 <= j && 26 > j) printf("%c", j+'A');
else if ( 26 == j ) printf("_");
else if ( 27 == j ) printf(".");
else if ( 28 == j ) printf(",");
else if ( 29 == j ) printf("?");
p+=len;
}
putchar(10);
}
}
return 0;
}