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 (2N100). 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、如果下标超出,返回
    2、如果某一个字符串中后缀字符不同,返回
    3、添加这个字符,递归比较下一个
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
#include<climits>
using namespace std;
vector<string>vt;
string result="";
void findSuffix(int index)
{
    if(index>=vt[0].size())
        return;
    char c=vt[0].at(vt[0].size()-index-1);
    for(int i=0; i<vt.size(); i++)
    {
        if(index>=vt[i].size())
            return;
        if(vt[i].at(vt[i].size()-index-1)!=c)
                return;

    }
    result=c+result;
   // cout<<result<<endl;
    findSuffix(index+1);
}


int main()
{
    int n;
    scanf("%d",&n);
    vt.resize(n);
    getchar();
    for(int i=0; i<n; i++)
    {

        getline(cin,vt[i]);
    }
    findSuffix(0);
    if(result.size()==0)
        cout<<"nai"<<endl;
    else
        cout<<result;
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/zhanghaijie/p/10335511.html