AcWing 779. 最长公共字符串后缀
原题链接
困难
作者:
逆时针
,
2020-08-10 21:32:52
,
所有人可见
,
阅读 654
C++ 代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int N;
while (cin >> N && N != 0) {
vector<string> vs;
string s;
cin >> s;
vs.push_back(s);
int min_length = s.size();
// 找出最短的字符串长度min_length
for (int i = 1; i != N; ++i) {
cin >> s;
vs.push_back(s);
if (s.size() < min_length)
min_length = s.size();
}
int common_suffix_length = 0;
bool is_common_suffix = true;
// 最多比较min_length次
for (int i = 0; i != min_length; ++i) {
// 遍历vector<string>,比较各string当前位置(指从末端反向过来第i个)的字符是否相同
for (int j = 1; j != vs.size(); ++j) {
int idx1 = vs[j].size() - 1 - i;
int idx2 = vs[j-1].size() - 1 - i;
// 当前位置不同,共同后缀止步于此
if (vs[j][idx1] != vs[j-1][idx2]) {
is_common_suffix = false;
break;
}
}
if (!is_common_suffix)
break;
// 所有string当前位置均相同,共同后缀加1
++common_suffix_length;
}
string max_common_suffix = vs[0].substr(vs[0].size() - common_suffix_length, common_suffix_length);
if (max_common_suffix.size() != 0)
cout << max_common_suffix << endl;
else
cout << endl;
}
return 0;
}