原题链接:
https://pintia.cn/problem-sets/994805342720868352/exam/problems/type/7?problemSetProblemId=994805390896644096&page=0
注意点:
- 这道题我在没有去掉ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);发现相同代码在我的Visual Studio 2022和PAT网站出现了输出结果不一致的情况,注释掉这一部分代码后,问题解决,编译通过。但是,当我找原因时,发现ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);的注意事项有不能使用getchar(),在将getchar()用cin替换掉后,还是有一个测试点没过,经过检查,发现使用cin会吞掉第一行输入的第一个char更换为cin.ignore()后,问题解决。
代码:
#include <iostream>
#include <string>
using namespace std;
#define endl '\n'
int N;
string spoke[100];
int same = -1;//记录找到了哪一位
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> N;
int minLen = 256;
cin.ignore();
for (int i = 0; i < N; i++) {
getline(cin, spoke[i]);
if (spoke[i].size() < minLen) {
minLen = spoke[i].size();
}
}
bool flag = true;//代表是否需要继续判断
for (int i = 0; i < minLen; i++) {//判断倒数第i+1位是否相同
if (!flag) {
break;
}
char now = spoke[0][spoke[0].size() - i - 1];
for (int j = 1; j < N; j++) {
if (spoke[j][spoke[j].size() - i - 1] != now) {
flag = false;
break;
}
}
if (flag) {
same++;
}
}
if (same == -1) {
cout << "nai";
}
else {
for (int i = same; i >= 0; i--) {
cout << spoke[0][spoke[0].size() - i - 1];
}
}
return 0;
}