Longest Palindromic Substring

来源:互联网 发布:男主很帅的动漫 知乎 编辑:程序博客网 时间:2024/06/01 08:23

Q:

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.


Solution:

public class Solution {    public String longestPalindrome(String s) {        if (s == null)            return null;        if (s.length() <= 1)            return s;        int start = 0;        int max = 1;        for (int n = 1; n < s.length(); n++) {            int i = n - 1;            int j = n + 1;            int l = 1;            while (i >= 0 && s.charAt(i) == s.charAt(n))                i--;            while (j <= s.length()-1 && s.charAt(j) == s.charAt(n))                j++;            while (i >= 0 && j <= s.length()-1 && s.charAt(i) == s.charAt(j)) {                i--;                j++;            }            l = j - i - 1;            if (l > max) {                start = i;                max = l;            }        }        return s.substring(start+1, start+1+max);    }}


0 0
原创粉丝点击