1077. Kuchiguse (20)

思路

将每一行的逆序存放在strs中,然后找strs中的所有line的相同前缀。

代码

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    scanf("%d",&n);
    int enter;// the '\n' followed n
    scanf("%c",&enter);
    vector<string> strs;
    while(n--)// push back all the lines
    {
        char tmpc[266];
        int pos=0;
        while(scanf("%c",&tmpc[pos]) && tmpc[pos] !='\n') pos++;
        tmpc[pos] = '\0';
        string tmp = tmpc;
        reverse(tmp.begin(),tmp.end());
        strs.push_back(tmp);
    }

    int pos = 0;
    bool flag=true;
    while(flag)
    {
        char target = strs[0][pos];
        for(int i=1;i<strs.size();++i)
        {
            if(pos < strs[i].size())
            {   
                if(strs[i][pos] != target) 
                {flag= false;break;}
            }
            else {flag= false;break;}//exceed the size of strs[i]
        }
        pos++;
    }
    string result = strs[0].substr(0,pos-1);
    reverse(result.begin(),result.end());
    if(result.size())
        cout<<result<<endl;
    else
        cout<<"nai"<<endl;
    return 0;
}