【LeetCode-面試演算法經典-Java實現】【005-Longest Palindromic Substring(最長迴文子串)】,-javapalindromic

來源:互聯網
上載者:User

【LeetCode-面試演算法經典-Java實現】【005-Longest Palindromic Substring(最長迴文子串)】,-javapalindromic
【005-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.

題目大意

  給定一個字串S,找出它的最大的迴文子串,你可以假設字串的最大長度是1000,而且存在唯一的最長迴文子串

解題思路

  動態規劃法,
  假設dp[ i ][ j ]的值為true,表示字串s中下標從 i 到 j 的字元組成的子串是迴文串。那麼可以推出:
  dp[ i ][ j ] = dp[ i + 1][ j - 1] && s[ i ] == s[ j ]。
  這是一般的情況,由於需要依靠i+1, j -1,所以有可能 i + 1 = j -1, i +1 = (j - 1) -1,因此需要求出基準情況才能套用以上的公式:
  a. i + 1 = j -1,即迴文長度為1時,dp[ i ][ i ] = true;
  b. i +1 = (j - 1) -1,即迴文長度為2時,dp[ i ][ i + 1] = (s[ i ] == s[ i + 1])。
  有了以上分析就可以寫出代碼了。需要注意的是動態規劃需要額外的O(n^2)的空間。

代碼實現
public class Solution {    /**     * 005-Longest Palindromic Substring(最長迴文子串)     *     * @param s 輸入的字串     * @return 最長迴文子串     */    public String longestPalindrome(String s) {        if (s == null || s.length() < 2) {            return s;        }        int maxLength = 0;        String longest = null;        int length = s.length();        boolean[][] table = new boolean[length][length];        // 單個字元都是迴文        for (int i = 0; i < length; i++) {            table[i][i] = true;            longest = s.substring(i, i + 1);            maxLength = 1;        }        // 判斷兩個字元是否是迴文        for (int i = 0; i < length - 1; i++) {            if (s.charAt(i) == s.charAt(i + 1)) {                table[i][i + 1] = true;                longest = s.substring(i, i + 2);                maxLength = 2;            }        }        // 求長度大於2的子串是否是迴文串        for (int len = 3; len <= length; len++) {            for (int i = 0, j; (j = i + len - 1) <= length - 1; i++) {                if (s.charAt(i) == s.charAt(j)) {                    table[i][j] = table[i + 1][j - 1];                    if (table[i][j] && maxLength < len) {                        longest = s.substring(i, j + 1);                        maxLength = len;                    }                } else {                    table[i][j] = false;                }            }        }        return longest;    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/46922011】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.