您的位置:首页 > 其它

LeetCode 5:Longest Palindromic Substring(最长回文串)

2015-06-11 22:54 387 查看
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

思路一:(超时)简单的截取长度为length(length递减)的字串,判断其是否为回文串。第一个满足要求的回文串最长。

public class Solution {
public String longestPalindrome(String s) {
int n = s.length();
int start = 0;
int maxLength = 1;
boolean dp[][] = new boolean[n+1][n+1];
for (int i = 0; i < n; i++) {
dp[i][i] = true;
}
for (int i = 0; i < n-1; i++) {
if (s.charAt(i) == s.charAt(i+1)) {
dp[i][i+1] = true;
start = i;
maxLength = 2;
}
}
for (int len = 3; len <= n; len++) {
for (int i = 0; i < n-len+1; i++) {
int j = i+len-1;
if (s.charAt(i) == s.charAt(j)&& dp[i+1][j-1]) {
dp[i][j] = true;
start = i;
maxLength = len;
}
}
}
return s.substring(start, start+maxLength);

}

}


View Code
思路三:http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html这个方法效率最高,现在的水平还想不出这样的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: