1077 Kuchiguse (20point(s)) - C語言 PAT 甲級

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. 用指針數組記錄每個字符串的尾地址,
  2. 用第一個字符串依次和其他字符串進行比較,尾字符相同,指針前移,
    1. 比較次數以最短字符串爲準,防止越界
    2. 若公共後綴即爲最短字符串,此時指針會在最短字符串的前 1 位置,所以指針要加 1 後輸出,例如:
    3. ced 和 abcde 比較完成後,指針在 c 前面
  3. 輸出最後指針所在的字符串即爲公共後綴
編譯器: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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章