1077 Kuchiguse (20point(s))
The Japanese language is notorious for its sentence ending particles. Personal preference of such particles can be considered as a reflection of the speaker's personality. Such a preference is called "Kuchiguse" and is often exaggerated artistically in Anime and Manga. For example, the artificial sentence ending particle "nyan~" is often used as a stereotype for characters with a cat-like personality:
- Itai nyan~ (It hurts, nyan~)
- Ninjin wa iyada nyan~ (I hate carrots, nyan~)
Now given a few lines spoken by the same character, can you find her Kuchiguse?
Input Specification:
Each input file contains one test case. For each case, the first line is an integer N (2≤N≤100). Following are N file lines of 0~256 (inclusive) characters in length, each representing a character's spoken line. The spoken lines are case sensitive.
Output Specification:
For each test case, print in one line the kuchiguse of the character, i.e., the longest common suffix of all N lines. If there is no such suffix, write
nai
.Sample Input 1:
3 Itai nyan~ Ninjin wa iyadanyan~ uhhh nyan~
Sample Output 1:
nyan~
Sample Input 2:
3 Itai! Ninjinnwaiyada T_T T_T
Sample Output 2:
nai
寻找n(n > 2)个字符串的最长公共后缀:
多个字符串同时比较比较麻烦,可以考虑将两两比较,寻找最长公共后缀串。写一个函数进行寻找与判断即可。
(为了方便比较,可以将两个串反转来寻找,结果再反转回去即可。
反转函数直接调用 "algorithm" 库中的 reverse 函数)
此函数如下:
/* 寻找s1、s2最长公共后缀
* 如果有返回true,并将结果存入s中
* 如果没有返回false */
bool FindMaxSuffix(char s1[], char s2[], char s[]) {
int len1 = strlen(s1);
int len2 = strlen(s2);
reverse(s1, s1 + len1); //反转字符串1
reverse(s2, s2 + len2); //反转字符串2
int count = 0;
while (s1[count] == s2[count] && count < len1 && count < len2) {
s[count] = s1[count];
count++;
}
if (count == 0)
return false;
s[count] = '\0';
reverse(s, s + count);
return true;
}
🔺 大致思路:
- 先找出两个字符串的最长公共后缀存入ans中
- 然后用ans依次和后面的字符串寻找最长公共后缀,且更新存入ans。
最终所有串的最长公共后缀就在ans中了。
注意:如果中途一旦出现查找不到公共后缀,则说明这些串没有公共后缀。
完整代码:
//
// Created by LittleCat on 2020/2/10.
//
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 260
/* 寻找s1、s2最长公共后缀
* 如果有返回true,并将结果存入s中
* 如果没有返回false */
bool FindMaxSuffix(char s1[], char s2[], char s[]) {
int len1 = strlen(s1);
int len2 = strlen(s2);
reverse(s1, s1 + len1); //反转字符串1
reverse(s2, s2 + len2); //反转字符串2
int count = 0;
while (s1[count] == s2[count] && count < len1 && count < len2) {
s[count] = s1[count];
count++;
}
if (count == 0)
return false;
s[count] = '\0';
reverse(s, s + count);
return true;
}
int main() {
int n;
scanf("%d\n", &n);
char str1[N], str2[N];
char ans[N], temp[N]; //ans用于存储当前最长公共后缀,temp用于临时储存
cin.getline(str1, N);
cin.getline(str2, N);
FindMaxSuffix(str1, str2, ans); //先找出前两串的最长公共后缀,存入ans中
/* 依次输入后面的串 */
for (int i = 2; i < n; i++) {
cin.getline(str1, N);
//找出ans与输入的串的最长公共后缀,存入temp中
if (!FindMaxSuffix(str1, ans, temp)) {
//如果找不到
printf("nai\n");
return 0; //结束程序
}
strcpy(ans, temp); //将temp拷贝入ans中
}
printf("%s", ans);
return 0;
}
end
欢迎关注个人公众号“ 鸡翅编程 ”,这里是认真且乖巧的码农一枚。
---- 做最乖巧的博客er,做最扎实的程序员 ----
旨在用心写好每一篇文章,平常会把笔记汇总成推送更新~