PAT-A-1077 Kuchiguse

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~
代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn=110;
int main(){
    string word[maxn],rev[maxn];//用于保存反转的字符串
    int n;
    scanf("%d",&n);
    getchar();
    for(int i = 0 ; i < n ; i ++){
        getline(cin,word[i]);
        rev[i]=word[i];
        reverse(rev[i].begin(),rev[i].end());
    }
    // cout<<"------"<
    // for(int i = 0 ; i < n ; i ++){
    //     cout<
    // }
    int minLen=0x3fffffff;
    for(int i = 0 ; i < n ; i ++){
        int len=rev[i].length();
        if(minLen>len){
            minLen=len;
        }
    }
    int commomLen=0;
    bool flag=true;
    for(int i = 0 ; i < minLen ; i ++){//在最小长度内遍历每个字符,求最长公共前缀的长度
        char c=rev[0][i];
        for(int j = 1 ; j < n ; j ++){
            if(c!=rev[j][i]){
                flag=false;
                break;//退出
            }
        }
        if(flag==false){
            break;
        }
        commomLen++;
    }
    // cout<
    if(commomLen==0){
        printf("nai");
    }else{
        for(int i = word[0].length()-commomLen ; i <=word[0].length()-1  ; i ++){
            printf("%c",word[0][i]);
        }
    }
    // system("pause");
    return 0;
}

你可能感兴趣的:(字符串,PAT)