题目大意:给定一个字符串,先用Morse Code编码,把编码倒序,再解码成字符串。现给定处理后的字符串,求原始信息。
解法:用C++String类的函数。每次读入一个字符,就在string后面接上,并且保存字符对应morse码的长度。这里要声明一下,真正的morse码也是有句号、问号这些常用标点符号的,但不是题目里给出的那种形式。比如,句号是“.-.-.-”。
参考代码:
#include<iostream> #include<string> using namespace std; string code[30]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---", "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-", "...-",".--","-..-","-.--","--..","..--",".-.-","---.","----"}; int main(){ int i,j,k,len,n,num[100],cases=0; string str,ss; cin>>n; while(n--){ cases++; cin>>str; len=str.length(); i=0; string morse=""; while(i<len){ if(str[i]>64&&str[i]<91){ morse.append(code[str[i]-'A']); num[len-1-i]=code[str[i]-'A'].size(); } else{ switch(str[i]){ case '_': morse.append("..--");break; case ',': morse.append(".-.-");break; case '.': morse.append("---.");break; case '?': morse.append("----");break; } num[len-1-i]=4; } i++; } i=j=0; while(i<len){ k=0; ss=morse.substr(j,num[i]); j+=num[i]; if(ss=="..--"){str[i++]='_';continue;} if(ss==".-.-"){str[i++]=',';continue;} if(ss=="---."){str[i++]='.';continue;} if(ss=="----"){str[i++]='?';continue;} while(k<26){ if(ss.compare(code[k])==0){ str[i++]=k+'A'; break; } k++; } } cout<<cases<<": "<<str<<endl; } return 0; }