PAT-A 1077 Kuchiguse (20 分)

1077 Kuchiguse (20 分)

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

思路:

1.题意是,给定n个字符串,输出这n个字符串的最大公共后缀。

2.将所有的字符串逆置,正序比较,直到出现第一个不同的字符为止。

3.使用string的getline方法读入一行。

#include <string>
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    int n;
    cin >> n;
    getchar();

    string in[n];
    for(int i = 0; i < n; i++)
    {
        getline(cin, in[i]);//读入一行字符串
        reverse(in[i].begin(), in[i].end());//将读入的字符串逆转
    }
    //计算最短的字符串的长度
    int min_size = in[0].size();
    for(int i = 1; i < n; i++)
        if(min_size < in[i].size())
            min_size = in[i].size();
    int num = 0;//公共后缀的长度
    bool flag = true;//标记是否出现非公共字符
    for(int i = 0; i < min_size; i++)//从最后一个字符开始比较
    {
        for(int j = 1; j < n; j++)
        {
            if(in[j][i] != in[0][i])
            {   //出现一对不等的字符
                flag = false;
                break;
            }
        }
        if(flag)//所有字符串对应位置字符都相同
            num++;//公共后缀长度加一
        else  //出现第一个非公共字符,不再比较
            break;
    }
    if(0 == num)//没有公共后缀
        printf("nai");
    else
    {
        while(num--)
            printf("%c", in[0][num]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38127801/article/details/86319609