解题思路:y总nb。
遍历一组字符串,逐个字符比较末尾字符,找到最长的公共后缀。
找到最短字符串长度,然后从末尾向前比较字符,直到所有字符串末尾字符不同或到达最短长度为止。
最后输出最长公共后缀。
#include <iostream>
using namespace std;
const int N = 200;//定义常量n为100
int main() {
int n;
string str[N];//定义字符串,最长为200
while (cin >> n, n) {
int len = 1000;//定义len并赋值1000,用于找出最短len
for (int i = 0; i < n; i++) {
cin >> str[i];
if (len > str[i].size())
len = str[i].size();//找出最短字符串,若比len短则更新
}
while (len) {//当len不等于0时
bool success = true;//定义一个bool变量success为true
for (int i = 1; i < n; i++) {
bool is_same = true;//定义一个bool量is same
for (int j = 1; j <= len; j++) {
if (str[0][str[0].size() - j] != str[i][str[i].size() - j]) {//用最短长度len比较。比较对象为第一行和第i行
is_same = false;//若不同则is same变为false
break;//跳出此次循环
}
}
if (!is_same) {//若is same是false则success也变为flase
success = false;
break;//跳出循环
}
}
if (success)//若success是true
break;//跳出这一轮循环
len--;//如果上一步没有找到公共后缀,将len减1
}
cout << str[0].substr(str[0].size() - len) << endl;//输出第一个字符串的末尾len个字符,即最长公共后缀
}
return 0;