PAT-A 1077,题目地址:https://www.patest.cn/contests/pat-a-practise/1077
思路如下:
- 将所有字符串进行翻转操作
- 从第0个字符开始逐个比较所有字符串相同位置的字符,直到有的字符串结束或遇到不同字符
- 记录最后一个相同的字符的下标index
- 输出相同的字符串,如果index为0则说明没有共同的suffix,则输出nai
注意:输入时处理输入n之后的回车。由于字符串中有空格,需要使用gets,getline等读入一整行的字符的函数,因此在输入n之后必须有一个getchar读掉n之后的回车,否则这个回车会被当做一个字符串
代码:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
string reverse(string a){ //字符串翻转
int len = a.size();
string res;
for(int i = len - 1; i >= 0;i--){
res.push_back(a[i]);
}
return res;
}
int main(){
int n;
cin >> n;
getchar(); //读取多余的回车
string strs[100];
for(int i = 0; i < n; i++){
string tmp;
getline(cin, tmp);
strs[i] = reverse(tmp);
}
bool equal = true;
int index = 0;
while(1){
for(int i = 1; i < n; i++){
if(index > strs[i].size() - 1|| index > strs[0].size() - 1 || strs[i][index] != strs[0][index]){
equal = false;
break;
}
}
if(!equal)
break;
index++;
}
if(index == 0)
cout << "nai" << endl;
else{
for(int i = index - 1; i >= 0; i--)
putchar(strs[0][i]);
putchar('\n');
}
return 0;
}





网友评论