5Longest Palindromic Substring

来源:互联网 发布:怎么做图书marc数据 编辑:程序博客网 时间:2024/05/01 18:31

题目链接:https://leetcode.com/problems/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.

解题思路:
每遍历一个字符,分两种情况来查找回文。
第一种情况(回文长度为奇数),以该字符为中心,判断其两侧字符是否相等,即 i - 1 和 i + 1。
第二种情况(回文长度为偶数),以该字符及其右侧邻接字符为中心,判断两边字符是否相同,即 i,i + 1。
时间复杂度 O(n2)

注意:
回文有分奇数长度和偶数长度两种情况,不要考虑漏了。

public class Solution {    public String longestPalindrome(String s) {        if(s == null || s.length() == 0)            return s;        int len = s.length();        int start = 0;        int end = 0;        int maxLen = 0;        for(int i = 0; i < len; i ++) {            int j = 1;//寻找以i-1,i+1为中点奇数长度的回文            while(i - j >= 0 && i + j < len) {                if(s.charAt(i - j) == s.charAt(i + j)) {                    if(2 * j + 1 > maxLen) {                        maxLen = 2 * j + 1;                        start = i - j;                        end = i + j;                    }                } else {                    break;                }                j ++;            }            int k = 1;//寻找以i,i+1为中点偶数长度的回文            while(i - (k - 1) >=0 && i + k < len) {                if(s.charAt(i - k + 1) == s.charAt(i + k)) {                    if(2 * k > maxLen) {                        maxLen = 2 * k;                        start = i - k + 1;                        end = i + k;                    }                } else                    break;                k ++;            }        }        return s.substring(start, end + 1);    }}
88 / 88 test cases passed.Status: AcceptedRuntime: 360 ms
0 0
原创粉丝点击