LeetCode:Longest Palindromic Substring
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode: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.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:Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode]Longest Palindromic Substring
leetcode longest consecutive sequence
LeetCode Longest Increasing Subsequence