[LeetCode] Longest Palindromic Substring

来源:互联网 发布:软件项目生命周期图 编辑:程序博客网 时间:2024/05/01 16:54

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.

思路:两种思路 ,一种是常规思路,从每个位置向两遍扩展,找到最长回文字串,不过要注意区分偶数和奇数的中心位置。

第二种思路是动态规划, dp[i][j] = dp[i + 1][j - 1] && s[i] == s[j],且 i >= j 为true


public class Solution {    public String longestPalindrome(String s) {        if (s == null || s.length() < 1) {            return null;        }                String res = "";                for (int i = 0; i < 2 * s.length() - 1; i++) {            int left = i / 2;            int right = i / 2;            if (i % 2 == 1) {                right++;            }                        String str = getMaxPalindromicString(s, left, right);            if (str.length() > res.length()) {                res = str;            }        }                return res;    }        private String getMaxPalindromicString(String s, int left, int right) {        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {            left--;            right++;        }                return s.substring(left + 1, right);    }}


0 0