查找两个字符串之间最长的公共后缀C++
Finding the longest common suffix between two strings C++
我对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";
}
相关文章:
- 增量运算符与后缀混淆
- 如何在OpenSSL库的名称中添加后缀'd'?
- C++17 十六进制浮点文字单精度后缀冲突?
- 使用带有链表的堆栈数据结构将中缀转换为后缀
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- 为什么 C++ 程序员更喜欢前缀 ++,而 Java 程序员更喜欢后缀 ++?
- 在qt QFileDialog中设置后缀在linux中不起作用,如何解决?
- 用于自定义调试构建的 CMake qt 输入库后缀
- 组合"%"和可选后缀时,自动属性传播有时不起作用
- 中缀后缀转换C ++,似乎无法得到正确的答案
- C++中的后缀不像我期望的那样表现
- 广义后缀树遍历以查找最长的公共子字符串
- C++ 后缀评估问题
- 后缀 "&" (地址) 运算符 在 C++ 中
- 堆栈后缀表示法评估等于中缀计算得到的不同
- 后缀 ++ 的优先级
- C++是否可以将宏重写浮点文本为双文本或至少删除 f 后缀?
- 导致错误的后缀和前缀增量
- 如何从LCP数组和后缀数组构造后缀树
- 玛丽莎·特里后缀压缩?