PAT甲级1077 Kuchiguse (20分)|C++实现

一、题目描述

原题链接
The ranklist of PAT is generated from the status list, which shows the scores of the submissions. This time you are supposed to generate the ranklist for PAT.

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

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

二、解题思路

字符串处理题,要求我们找出最长的共用后缀。对于这个题,我们可以每次只对一个字符串进行操作,将当前的相同后缀存放在ans中,这个比较的过程,放在check函数中,当ans的size为0时,我们就直接把当前的str传给ans,这一步主要是做初始化,因为如果后面的过程中ans为0了,我们可以直接在主函数中判断,打印nai,return 0即可。

三、AC代码

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
using namespace std;
string ans;
void check(string str)
{
    
    
    int sze = ans.size(), sze2 = str.size();
    string tmp = "";
    if(sze == 0)
    {
    
    
        ans = str;
        return;
    }
    else
    {
    
    
        for(int i=1; i<=min(sze, sze2); i++)
        {
    
    
            if(ans[sze-i] == str[sze2-i])
                tmp += ans[sze-i];
            else
                break;
        }
    }
    reverse(tmp.begin(), tmp.end());
    ans = tmp;
    return;
}
int main()
{
    
    
    int N;
    scanf("%d", &N);
    getchar();
    string str[N];
    for(int i=0; i<N; i++)
    {
    
    
        getline(cin, str[i]);
        check(str[i]);
        if(ans.size() == 0) //出现了一次ans为空,则直接打印nai,返回即可。
        {
    
    
            printf("nai\n");
            return 0;
        }
    }
    cout << ans << endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108745707