# 【LeetCode练习】[中等]5. 最长回文子串

10/19 11:14

【LeetCode练习】[中等]5. 最长回文子串

# 5. 最长回文子串

## 暴力解法–超时

``````class Solution {

public String longestPalindrome(String s) {

String reString = "";
for (int i = 0; i < s.length(); i++) {

for (int j = i; j < s.length(); j++) {

String strtemp = s.substring(i,j+1);//找到每一个子串
if(isPalindrome(strtemp) && strtemp.length() > reString.length()) {

//判断该子串是否是回文串,并记录长度最大的子串
reString = strtemp;
}
}
}
return reString;
}

public boolean isPalindrome(String s) {

//判断是否是回文串
char[] schar = s.toCharArray();
int len = s.length();
int i = 0;
int j = len - 1;
for (; i < j; i++,j--) {

if(schar[i] != schar[j]) {

return false;
}
}
return true;
}
}
``````

## java代码–动态规划

``````public String longestPalindrome(String s) {

int n = s.length();
boolean[][] dp = new boolean[n][n];
String ans = "";
for (int len = 0; len < n; ++len) {

//回文串长度,从0开始,最大为n
for (int i = 0; i + len < n; ++i) {

//回文串起始下标i
int j = i + len;//终止下标j
if (len == 0) {

dp[i][j] = true;
} else if (len == 1) {

dp[i][j] = (s.charAt(i) == s.charAt(j));
} else {

dp[i][j] = (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]);
}
if (dp[i][j] && len + 1 > ans.length()) {

ans = s.substring(i, i + len + 1);//len+1是回文串长度
}
}
}
return ans;
}
``````

0
0 收藏

0 评论
0 收藏
0