延伸至回文

Extend to Palindrome

本文关键字:回文      更新时间:2023-10-16

为了解决UVa 11475 - 扩展到回文 我想出了以下算法:

#include <algorithm>
#include <iostream>
using namespace std;
int main() {
    string word;
    while (cin >> word) {
        unsigned long i(0), j(word.size() - 1);
        while (i < j) {
            if (word[i] != word[j])
                word.insert(j + 1, 1, word[i]);
            else
                j--;
            i++;
        }
        cout << word << endl;
    }
    return 0;
}

但结果是"错误的答案",尽管代码为示例输入提供了正确的输出。那么我在这里错过了什么?什么样的测试用例可能导致这种情况?

我的教授告诉我们检查 KMP 算法,作为提示,但我不明白字符串搜索算法与检查字符串是否回文有什么关系。

例如,

在测试中检查您的程序

阿德巴德

它给出了错误的答案