码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Palindromic Substring——LeetCode

时间:2015-04-08 00:54:17      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

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);
    }

 

Longest Palindromic Substring——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4401146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!