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

时间:2013-10-27 00:46:11

标签: c++ arrays loops

我对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;
    }

2 个答案:

答案 0 :(得分:1)

有几件事:

  • 您应该更好地使用string而不是char数组。那样, 你不必担心记忆。
  • k=0;行应位于while
  • 之外
  • 请记住,数组从0开始,因此从长度为1 单词并在len1 >= 0 && len2 >= 0
  • 时迭代
  • 使用字符串,您可以使用方法substr(参考 here)。

以下是您的代码的修改版本:

#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;
}

答案 1 :(得分:1)

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

#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";
}
相关问题