题目描述
给出若干个字符串,输出这些字符串的最长公共后缀。
C++ 代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int n;
while (true) {
cin >> n;
if (n == 0) break;
vector<string> words;
for (int i = 0; i < n; i++) {
string word;
cin >> word;
words.push_back(word);
}
string suffix = words[0];
for (int i = 1; i < words.size(); i++) {
string cur = words[i];
int j = suffix.size() - 1;
int k = cur.size() - 1;
string temp = "";
while (j >= 0 && k >= 0 && suffix[j] == cur[k]) {
temp = suffix[j] + temp;
j--;
k--;
}
suffix = temp;
}
cout << suffix << endl;
}
return 0;
}