PAT(Advanced) 1077 Kuchiguse 最长后缀 C++实现

PAT(Advanced) 1077 Kuchiguse 最长后缀 C++实现

题目链接

1077 Kuchiguse

题目大意

给定N个字符串,求最长公共后缀子串

AC代码

/*
author : eclipse
email  : [email protected]
time   : Mon Jan 25 15:59:09 2021
*/
#include <bits/stdc++.h>
using namespace std;

bool match(string suffix, string target) {
    
    
    int offset = target.size() - suffix.size();
    for (int i = 0; i < suffix.size(); i++) {
    
    
        if (target[offset + i] != suffix[i]) {
    
    
            return false;
        }
    }
    return true;
}

int main(int argc, char const *argv[]) {
    
    

    int N;
    scanf("%d", &N);
    getchar();

    vector<string> lines(N);
    string shortest = "";
    for (int i = 0; i < N; i++) {
    
    
        getline(cin, lines[i]);
        if (i == 0) {
    
    
            shortest = lines[i];
        } else if (shortest.size() > lines[i].size()) {
    
    
            shortest = lines[i];
        }
    }

    string suffix = "";
    int index = 0;
    
    while(suffix.size() < shortest.size()) {
    
    
        suffix = shortest[shortest.size() - 1 - index] + suffix;

        int count = 0;
        for (int i = 0; i < lines.size(); i++) {
    
    
            if (match(suffix, lines[i])) {
    
    
                count++;
            } else {
    
    
                break;
            }
        }

        if (count != lines.size()) {
    
    
            break;
        }

        index++;
    }



    if (index == 0) {
    
    
        printf("nai");
    } else {
    
    
        for (int i = shortest.size() - index; i < shortest.size(); i++) {
    
    
            printf("%c", shortest[i]);
        }
    }
    
    return 0;
}

样例输入1

3
Itai nyan~
Ninjin wa iyadanyan~
uhhh nyan~

样例输出1

nyan~

样例输入2

3
Itai!
Ninjinnwaiyada T_T
T_T

样例输出2

nai

鸣谢

PAT

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!

猜你喜欢

转载自blog.csdn.net/qq_44486439/article/details/113125235
今日推荐