Longest Palindromic Substring

来源:互联网 发布:java微信分享接口开发 编辑:程序博客网 时间:2024/06/06 12:53

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 == null) {            return null;        }        if (s.length() <= 1) {            return s;        }        int max = 0;        int start = 0;        int l = s.length();        //odd        for (int i = 1; i < l; i++) {            int left = i;             int right = i;            while (left >= 0 && right <l) {                if (s.charAt(left) != s.charAt(right)) {                    break;                }                left--;                right++;            }            if (max < right - left - 1) {                start = left + 1;                max = right - left - 1;            }         }        //even        for (int i = 0; i < l - 1; i++) {            int left = i;             int right = i + 1;            while (left >= 0 && right <l) {                if (s.charAt(left) != s.charAt(right)) {                    break;                }                left--;                right++;            }            if (max < right - left - 1) {                start = left + 1;                max = right - left - 1;            }         }        return s.substring(start, start + max);    }}
http://www.cnblogs.com/TenosDoIt/p/3675788.html
这道题目可以用递归来做,也可以分别求出 奇数长度的回文 和 偶数长度的回文长度,然后求出最大值。
还有一种O(N) 方法的,由于面试的时候很难想出来 就不实现了

0 0
原创粉丝点击