题目链接:
题目描述:
求字符串的最长公共后缀。
题目分析:
跟LeetCode上有道求字符串组的最长公共前缀没啥区别啊,就是反起来从后往前遍历。一边比较一边记录当前最长公共后缀的长度,下一个字符串与当前字符串比较得出来的最长公共后缀长度只可能比当前小或者等于。
代码:
#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main()
{
int N;
cin >> N;
getchar();
string str1,str2;
getline(cin,str1);
N = N - 1;
int longest = str1.size();
while (N--){
getline(cin, str2);
int i = str1.size()-1;
int j = str2.size() - 1;
int k = 0;
while (k < longest && str1[i--] == str2[j--]){
k++;
}
longest = k;
str1 = str2;
}
int n = str1.size();
if (longest == 0){
cout << "nai" << endl;
}
else{
string result = "";
for (int i = n - longest; i < n; i++){
result += str1[i];
}
cout << result << endl;
}
return 0;
}