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个 (2≤N≤100)字符串(长度0~256 ),求他们的公共后缀。如果不存在公共后缀,则输出“nai”.
思路:
本题中字符串的个数是给定的,很难直接定义,使用string类型的数组存储最好,这样也方便比较。
比较到最小长度也要注意。
注意:
- 公共后缀需要从后往前枚举字符串,因此可先将字符串反转,这样问题转换为求N个字符串的公共前缀
- 求得所有字符串的最短长度 minLen, 枚举在 minLen之内的字符,相同位置的字符相同,则累计
- 字符串中间存在空格,因此不可用 scanf (因为 scanf 函数的 %s 以空白格包括空格在内进行截断)
- getchar() 函数的使用:getchar()是在输入缓冲区顺序读入一个字符(包括空格、回车和Tab) ,前面的scanf()在读取输入时会在缓冲区中留下一个字符'\n',所以如果不在此加一个getchar()把这个回车符取走的话,getline()就不会等待从键盘键入字符,而是会直接取走这个“无用的”回车符,从而导致读取有误
- 题中输入很多字符串,采用C++的string类处理。getline属于string流,接收一个字符串,遇到‘\n’结束。begin()函数返回一个迭代器,指向字符串的第一个元素。end()函数返回一个迭代器,指向字符串的末尾(最后一个字符的下一个位置)。reverse()会将区间[beg,end)内的元素全部逆序(第二个参数是数组最后一个元素的下一个地址)。
#include <iostream> //需要使用C++中的string类
#include <cstdio>
#include <cstring>
#include <algorithm> //使用reverse函数
using namespace std;
int n, minLen = 256, ans = 0;
string s[256]; //定义string类型的数组
int main() {
scanf("%d", &n);
getchar();
for(int i = 0; i < n; i++) {
getline(cin, s[i]);
int len = s[i].size();
if(len < minLen) {
minLen = len;
}
reverse(s[i].begin(),s[i].end());
}
for(int i = 0; i < minLen; i++) {
char c = s[0][i];
bool same = true;
for(int j = 0; j < n; j++) {
if(c != s[j][i]) {
same = false;
break;
}
}
if(same) {
ans++;
} else {
break;
}
}
if(ans) {
for(int i = ans - 1; i >= 0; i--) {
printf("%c", s[0][i]);
}
} else {
printf("nai");
}
return 0;
}