Skip to content

Commit c184cb3

Browse files
authored
Update 5. Longest Palindromic Substring.cpp
1 parent e9e3264 commit c184cb3

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

5. Longest Palindromic Substring.cpp

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
class Solution {// better method, great answer
1+
class Solution {
22
public:
3-
string longestPalindrome(string s) {
4-
if (s.empty()) return "";
5-
int dp[s.size()][s.size()] = {0}, len = 0;
3+
string longestPalindrome(string s) {
4+
if(s.size()<=1) return s;
5+
vector<vector<int>>dp(s.size(), vector<int>(s.size(), 0));
6+
int len=0;
67
string res;
7-
for (int i = 0; i < s.size(); ++i) {
8-
for (int j = 0; j <= i; ++j) {
9-
// i - j < 2 应该在前,不然数组越界------没懂这意思
10-
dp[j][i] = (s[i] == s[j] && (i - j < 2 || dp[j + 1][i - 1]));
11-
if (dp[j][i] && len < i - j + 1) {
12-
len = i - j + 1;
8+
for (int i=0;i <s.size();i++){
9+
for (int j=0;j<=i;j++){
10+
dp[j][i]=(s[j]==s[i]) && (i-j<=1 || dp[j+1][i-1]);
11+
if(dp[j][i] && i-j+1>len){
12+
len=i-j+1;
1313
res = s.substr(j, len);
1414
}
15-
}
15+
}
1616
}
17-
return res;
17+
return res;
1818
}
1919
};
2020
//在之前有一个题目使用自下而上的解法

0 commit comments

Comments
 (0)