Longest Palindromic Substring
Longest Palindromic Substring
问题:
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.
思路:
动态规划
我的代码:
public class Solution { public String longestPalindrome(String s) { if(s == null || s.length() == 0) return s; int len = s.length(); boolean[][] dp = new boolean[len][len]; int start = 0; int max = 1; for(int i = 0; i < len; i++) { dp[i][i] = true; if(i < len- 1 && s.charAt(i) == s.charAt(i+1)) { max = 2; start = i; dp[i][i+1] = true; } } for(int size = 3; size <= len; size++) { for(int i = 0; i <= len-size; i++) { int j = i+size-1; if(dp[i+1][j-1] && s.charAt(i)==s.charAt(j)) { max = size; start = i; dp[i][j] = true; } } } return s.substring(start,start+max); } }
学习之处:
- 动归方程为dp[i][j] = (s.charAt(i) == s.charAt(j)) && dp[i+1][j-1] ? true : false;
- 想不出来动态规划的方程,就先想的dfs怎么做,然后再反向思维得出动态规划的方程,动态规划之所以快,是因为减少了好多的重复计算。
posted on 2015-04-03 16:32 zhouzhou0615 阅读(137) 评论(0) 编辑 收藏 举报