1077. Kuchiguse (20)

来源:互联网 发布:尖锐湿疣不治知乎 编辑:程序博客网 时间:2024/05/16 12:58

题目如下:

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:
    3Itai nyan~Ninjin wa iyadanyan~uhhh nyan~
    Sample Output 1:
    nyan~
    Sample Input 2:
    3Itai!Ninjinnwaiyada T_TT_T
    Sample Output 2:
    nai



  • 题目要求从一系列给定字符串中找出公共结尾,因为这个结尾将会被所有的字符串所共有,所以我们保存第一个输入的字符串,用它来和各个字符串比较,找出共同位置,一旦发现没有共同部分,立即返回nai,因为输入和输出流是分开的,所以我们提前返回得到的输出文件没有任何问题;如果发现了公共部分,就要进行保存,我们用一个suffix变量保存这个公共字串,当发现的公共部分长度比suffix小,说明公共部分缩短,应该更新,为了保证第一次的公共部分能够写入suffix,我们把suffix的值初始化为第一次输入。

    对于有空格的输入,应该使用getline(),getline()有个问题是会吃掉上一行的回车作为一个空行,因此getline()之前如果有输入一定要getchar()吃掉那个回车再处理

    代码如下:

    #include <iostream>#include <stdio.h>#include <string>#include <vector>using namespace std;int main(){    int N;    string temp,suffix,input;    cin >> N;    getchar();    getline(cin,temp);    suffix = temp;    for(int i = 1; i < N; i++){        getline(cin,input);        int tempCur = temp.length() - 1;        int inputCur = input.length() - 1;        while(input[inputCur] == temp[tempCur]){            inputCur--;            tempCur--;        }        int len = temp.length() - tempCur - 1;        if(len == 0){            suffix = "nai";            break;        }        if(suffix.length() > len){            suffix = temp.substr(tempCur + 1);        }    }    cout << suffix << endl;    return 0;}


    0 0