Longest Palindromic Substring——LeetCode

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,存在唯一的最长的回文子串,求这个回文子串。

解题思路:首先这个题有O(n)的解,是在http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html这里有详细的解释,本文的算法是O(n^2)的,中规中矩的做法。回文有两种,abba和aba,本文分别对子串以i为中心进行检查偶数和奇数哪个长,同时记录长度,下标,奇偶等信息。

Talk is cheap>>

  public String longestPalindrome(String s) {

        if (s == null || s.length() <= 1) {

            return s;

        }

        int max_len = 0, pos = 0;

        boolean odd = false;

        for (int i = 0; i < s.length(); i++) {

            int forward = i - 1;

            int backward = i + 1;

            int len = 0;

            while (forward >= 0 && backward < s.length() && s.charAt(forward) == s.charAt(backward)) {

                forward--;

                backward++;

                len++;

            }

            if (max_len < (len * 2 + 1)) {

                max_len = len * 2 + 1;

                odd = true;

                pos = i;

            }

            len = 0;

            forward = i;

            backward = i + 1;

            while (forward >= 0 && backward < s.length() && s.charAt(forward) == s.charAt(backward)) {

                forward--;

                backward++;

                len++;

            }

            if (max_len < len * 2) {

                max_len = len * 2;

                odd = false;

                pos = i;

            }

        }

        if (odd) {

            return s.substring(pos - (max_len - 1) / 2, pos + (max_len - 1) / 2 + 1);

        }

        return s.substring(pos - max_len / 2 + 1, pos + max_len / 2 + 1);

    }

 

你可能感兴趣的:(substring)