标签:
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.length()==0) return ""; if(s.length()==1) return s; String res = ""; int maxLen =0; boolean[][] palin = new boolean[s.length()][s.length()]; StringBuilder sb =new StringBuilder(); for(int i=s.length()-1;i>=0;i--){ for(int j=i;j<s.length();j++){ if(s.charAt(i)==s.charAt(j)&&(j-i<=2||palin[i+1][j-1])){ palin[i][j] = true; if(maxLen<j-i+1){ maxLen = j-i + 1; res = s.substring(i, j+1); } } } } return res; } }
LeetCode(5):Longest Palindromic Substring
标签:
原文地址:http://www.cnblogs.com/Lewisr/p/5255334.html