【LeetCode練習】[中等]5. 最長迴文子串
題目來源
演演算法思想:字串;
時間複雜度O(n^3),超時
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;
}
}
動態規劃法
分析來源
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;
}