leetcode Question5.Longest Palindromic Substring

来源:互联网 发布:linux grub.cfg 编辑:程序博客网 时间:2024/06/05 19:42

问题描述:给出一个字符串,返回该串的最长回文子串。


解答:

public class Solution {    public String longestPalindrome(String s) {        switch(s.length()){case 0:case 1:return s;case 2:if(s.charAt(0) == s.charAt(1))return s;elsereturn s.substring(0, 1);}        int m = 0, n = 0;        if(s.charAt(0) == s.charAt(1))        n = 1;        int j = 2;        while(j < s.length()){        if(s.charAt(j) == s.charAt(j-1)){        int[] res = longestPalindrome(s, j-1, j);        if(res[1]-res[0] > n-m){        m = res[0];        n = res[1];        }        }        if(s.charAt(j) == s.charAt(j-2)){        int[] res = longestPalindrome(s, j-2, j);        if(res[1]-res[0] > n-m){        m = res[0];        n = res[1];        }        }        ++j;        }        return s.substring(m, n+1);    }        static int[] longestPalindrome(String s, int i, int j){--i;++j;while(i >= 0 && j < s.length()){if(s.charAt(j) == s.charAt(i)){--i;++j;        }else        break;}return new int[]{i+1, j-1};}}