查找两个字符串之间最长的公共后缀C++

Finding the longest common suffix between two strings C++

本文关键字:C++ 后缀 之间 字符串 两个 查找      更新时间:2023-10-16

我对C++相当陌生,我似乎无法弄清楚这一点。

运行它时我得到一些奇怪的输出。我也在尝试以最简单的方式做到这一点。我将如何只打印后缀数组中的单词,而不是所有额外的东西。我已经尝试了多种方法来做到这一点,它们仍然出现。

    #include <iostream>
    #include <conio.h>
    #include <string>
    using namespace std;
    int main(){
        char word1[80];
        char word2[80];
        char suffix[80];
        cout << "Enter the first word: ";
        cin >> word1;
        cout << "Enter the first word: ";
        cin >> word1;
        int len1 = strlen(word1);
        int len2 = strlen(word2);
        while(len1 > 0 && len2 > 0 && word1[len1] == word2[len2]) {
            int k=0;
            suffix[k]=word1[len1];  
            k++;
            len1--;
            len2--;
        }

        for(int i=strlen(suffix);i>=0; i--){
            cout << suffix[i];
        }

        getch();
        return 0;
    }

几件事:

  • 您最好使用 string 而不是 char 数组。那边您不必担心内存。
  • 行 int k=0; 应位于while 之外。
  • 请记住,数组从 0 开始,因此从单词和迭代,同时len1 >= 0 && len2 >= 0
  • 使用字符串,可以使用方法substr(参考这里)。

下面是代码的修改版本:

#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main() {
    string word1,word2,suffix;
    cout << "Enter the first word: ";
    cin >> word1;
    cout << "Enter the first word: ";
    cin >> word2;
    int len1 = word1.size()-1;
    int len2 = word2.size()-1;
    int k=0;
    while(len1 >= 0 && len2 >= 0 && word1[len1] == word2[len2]) {
        len1--;
        len2--;
        k++;
    }
    suffix=word1.substr(word1.size()-k,k);
    cout << suffix;
    getch();
    return 0;
}

我一直认为"最简单的方法"是使用别人的作品。这里是编写利用标准库的程序的一种方法:

#include <algorithm>
#include <string>
#include <iostream>
std::string suffix(const std::string& a, const std::string& b) {
    size_t len = std::min(a.size(), b.size());
    auto its = std::mismatch(a.rbegin(), a.rbegin()+len, b.rbegin());
    return std::string(its.first.base(), a.end());
}
int main () {
    std::cout << suffix("December", "May") << "n";
    std::cout << suffix("January", "February") << "n";
    std::cout << suffix("April", "April") << "n";
}