Longest Palindromic Substring

关键在于写好helper

public class Solution {

    public String longestPalindrome(String s) {

        if(s==null) return null;

        if(s.length()==1) return s;

        

        String longest = s.substring(0,1); // because at least there are 2 elements in s

        

        for(int i=0;i<s.length();i++){

            String tmp = helper(s, i, i); // 中心对称外延,延伸出来的tmp为奇数位长度

            if(longest.length()<tmp.length())

                longest = tmp;

            

             tmp = helper(s,i, i+1); //中心对称外延,tmp为偶数长度

            if(longest.length()<tmp.length())

                longest = tmp;

        }

        

        return longest;

        

    

    }

    

    public String helper(String s, int b, int e){

        while(b>=0 && e< s.length()  && s.charAt(b)==s.charAt(e)){

            b--;

            e++;

        }

        return s.substring(b+1, e);

    }

}

 

你可能感兴趣的:(substring)