PAT_A 1077 Kuchiguse

PAT_A 1077 Kuchiguse

分析

题目要求找到输入字符串的公共后缀,因此在输入时反转在存储会方便后续的操作。由于字符串中包含空格,使用getline进行读入,且需要在输入N后使用get过滤换行符。

题目的描述

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

AC的代码

// #include<iostream>
// #include<vector>
// #include<cstring>
// #include<algorithm>
#include<bits/stdc++.h>
using namespace std;

int main(){
    int N,len=1000;
    vector<string > strs;
    cin>>N;
    cin.get();
    string kuchiguse ;
    while(N--){
        string t;
        getline(cin,t);
        reverse(t.begin(),t.end());
        if(t.length()<len){
            len = t.length();
        }
        strs.push_back(t);
    }
    for(int i=0;i<len;i++){
        int c=1;
        char t = strs[0][i];
        for(int j=1;j<strs.size();j++){
            if(t==strs[j][i]){
                c++;
            }
        }
        if(c==strs.size()){
            kuchiguse+=t;
        }
        else break;
    }
    if(kuchiguse.size()){
        reverse(kuchiguse.begin(),kuchiguse.end());
        cout<<kuchiguse<<endl;
    }
    else{
        cout<<"nai\n";
    }
    return 0;
}
posted @ 2022-01-24 22:56  ghosteq  阅读(201)  评论(0编辑  收藏  举报