This commit is contained in:
2022-11-30 18:20:36 +08:00
parent b13cfa00bb
commit 72555b19e0
132 changed files with 332 additions and 334 deletions

View File

@@ -17,7 +17,7 @@
// 把 dp 这张二维数组的表全部填好,然后在里面找最长的子字符串。
// 时间复杂度O(n^2) 因为总共有 n^2 个状态,计算每个状态需要的时间为 O(1)
// 空间复杂度O(n^2) 因为总共需要存储 n^2 个状态。
string Solution1::longestPalindrome(string s) {
string S0005::longestPalindrome1(string s) {
int len = s.length();
vector<vector<int>> dp(len, vector<int>(len));
@@ -79,20 +79,13 @@ string Solution1::longestPalindrome(string s) {
// “回文中心”实际上是两种边界情况,也就是说每个可能的结果都是由边界情况扩展开来的
// 因此我们可以遍历每个边界情况,对它进行扩展
typedef struct ResultStruct {
int left1; // 边界情况为长度为 1 的字符时,扩展完成后的左边界
int right1; // 边界情况为长度为 1 的字符时,扩展完成后的右边界
int left2; // 边界情况为长度为 2 的字符串时,扩展完成后的左边界
int right2; // 边界情况为长度为 2 的字符串时,扩展完成后的右边界
} Result;
// 输入为字符串和边界情况的那一点
// 返回值包含为扩展的结果
Result expand(string s, int i) {
S0005Result S0005::expand(string s, int i) {
int len = s.length();
if (i == len - 1) {
return Result{i, i, i, i};
return S0005Result{i, i, i, i};
}
// 边界情况为长度为 1 的字符时
@@ -117,13 +110,13 @@ Result expand(string s, int i) {
}
}
return Result{left1, right1, left2, right2};
return S0005Result{left1, right1, left2, right2};
}
string Solution2::longestPalindrome(string s) {
string S0005::longestPalindrome2(string s) {
int len = s.length();
int left = 0, right = 0;
Result result{0, 0, 0, 0};
S0005Result result{0, 0, 0, 0};
for (int i = 0; i < len; i++) {
result = expand(s, i);
if (result.right1 - result.left1 > right - left) {