PAT1077 Kuchiguse (20)

本文介绍了一种求解字符串集合中最长公共后缀的方法,通过逆序比较字符串来逐步缩小最长公共后缀的范围,最终输出最长公共后缀。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

http://www.nowcoder.com/pat/5/problem/4307

题目描述:

求字符串的最长公共后缀。

题目分析:

跟LeetCode上有道求字符串组的最长公共前缀没啥区别啊,就是反起来从后往前遍历。一边比较一边记录当前最长公共后缀的长度,下一个字符串与当前字符串比较得出来的最长公共后缀长度只可能比当前小或者等于。

代码:
#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main()
{
    int N;
    cin >> N;
    getchar();
    string str1,str2;
    getline(cin,str1);
    N = N - 1;
    int longest = str1.size();
    while (N--){
        getline(cin, str2);
        int i = str1.size()-1;
        int j = str2.size() - 1;
        int k = 0;
        while (k < longest && str1[i--] == str2[j--]){
            k++;
        }
        longest = k;
        str1 = str2;
    }
    int n = str1.size();
    if (longest == 0){
        cout << "nai" << endl;
    }
    else{
        string result = "";
        for (int i = n - longest; i < n; i++){
            result += str1[i];
        }
        cout << result << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值