标签:
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); } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4390429.html