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:
3
Itai nyan~
Ninjin wa iyadanyan~
uhhh nyan~
Sample Output:
nyan~
Sample Input:
3
Itai!
Ninjinnwaiyada T_T
T_T
Sample Output:
nai
题目大意:
输入 N 行字符串,输出所有字符串的公共后缀,若没有则输出 nai
设计思路:
- 用指针数组记录每个字符串的尾地址,
- 用第一个字符串依次和其他字符串进行比较,尾字符相同,指针前移,
- 比较次数以最短字符串为准,防止越界
- 若公共后缀即为最短字符串,此时指针会在最短字符串的前 1 位置,所以指针要加 1 后输出,例如:
- ced 和 abcde 比较完成后,指针在 c 前面
- 输出最后指针所在的字符串即为公共后缀
编译器:C (gcc)
#include <stdio.h>
#include <string.h>
int main(void)
{
int n;
char a[100][258], *b[100], *result;
int i, j, len, min = 10000;
scanf("%d", &n);
getchar();
for (i = 0; i < n; i++) {
gets(a[i]);
len = strlen(a[i]);
b[i] = a[i] + len - 1;
if (len < min)
min = len;
}
int flag = 1;
for (i = 0; i < min; i++) {
for (j = 1; j < n; j++) {
if (*b[0] == *b[j]) {
b[j]--;
} else {
flag = 0;
break;
}
}
if (flag) {
b[0]--;
} else {
b[0]++;
break;
}
}
if (flag)
puts(b[0] + 1);
else if (*(b[0]) == '\0')
puts("nai");
else
puts(b[0]);
return 0;
}