题解 | #所有的回文子串II#
所有的回文子串II
https://www.nowcoder.com/practice/3373d8924d0e441987650194347d3c53
大家好,我是开车的阿Q,自动驾驶的时代已经到来,没时间解释了,快和阿Q一起上车。作为自动驾驶系统工程师,必须要有最好的C++基础,让我们来一起刷题吧。
题目考察的知识点
回文子串,字符串处理
题目解答方法的文字分析
我们需要找出给定字符串中的所有回文子串。为了解决这个问题,我们可以使用中心扩展法。对于每个字符,我们以它为中心,同时向左和向右扩展,直到找到回文串的边界。为了处理回文串长度为偶数的情况,我们可以选择一个中心点,也可以选择两个中心点。
例如:对于字符串 "abcba",我们可以以每个字符为中心向左右扩展,找到回文子串 "a", "b", "c", "b", "a", "abcba", "bcb"。
之后排除长度为1的字符串
然后,我们对找到的回文子串进行字典序排序,最后再去除重复的结果。
本题解析所用的编程语言
C++
完整且正确的编程代码
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> partitionII(string s) {
vector<string> result;
if (s.empty()) {
return result;
}
for (int i = 0; i < s.length(); ++i) {
// 以一个字符为中心向左右扩展,找到回文子串
expandAroundCenter(s, i, i, result);
// 以两个字符为中心向左右扩展,找到回文子串
expandAroundCenter(s, i, i + 1, result);
}
// 对结果进行字典序排序
sort(result.begin(), result.end());
// 去除重复的结果
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
private:
void expandAroundCenter(const string& s, int left, int right, vector<string>& result) {
while (left >= 0 && right < s.length() && s[left] == s[right]) {
// 添加找到的回文子串到结果中
if (right - left + 1 > 1) { // 排除长度为1的回文子串
result.push_back(s.substr(left, right - left + 1));
}
--left;
++right;
}
}
};
阿Q的题解 文章被收录于专栏
阿Q秋招刷过的题

查看11道真题和解析

