寻找最长回文子串的非最优C++代码测试不通过如何排查
最长回文子串代码问题修复
你枚举所有子串判断回文的实现思路是正确的,代码无法通过测试用例的核心问题出在API调用错误和命名空间遗漏两处:
1. 核心错误:substr参数使用错误
C++ std::string的substr方法定义为substr(起始下标, 子串长度),你把第二个参数当成了子串结束下标,导致生成的测试子串和预期完全不符。
2. 隐藏编译错误:缺少命名空间声明
string、reverse都属于std命名空间,你没有加对应的声明,代码会直接编译失败。
修复后可运行代码
#include <string> #include <algorithm> #include <iostream> using namespace std; class Solution { public: string longestPalindrome(string s) { string currentLongest = ""; int n = s.length(); if (n == 0) return currentLongest; for (int i = 0; i < n; i++) { // j为子串结束下标(左闭右开规则,可取到字符串总长度n) for (int j = i + 1; j <= n; j++) { // 第二个参数传入子串长度:结束下标 - 起始下标 string testcase = s.substr(i, j - i); string reversestring = testcase; reverse(reversestring.begin(), reversestring.end()); if (testcase == reversestring && testcase.length() > currentLongest.length()) { currentLongest = testcase; } } } return currentLongest; } };
补充说明
当前暴力枚举的时间复杂度为O(n³),仅适合短字符串场景,后续优化可优先改为中心扩展法(时间复杂度O(n²))或Manacher算法(时间复杂度O(n))。
内容的提问来源于stack exchange,提问作者Seasoned Potato
相关产品推荐
相关产品推荐

