Java AC solution with O(n2)


  • 0
    J
        public String longestPalindrome(String s) {
            int l = 0, r = 0;
            for(int i=0;i<s.length();i++){
                int single = longestWithCenter(i,i,s);
                int dou = longestWithCenter(i,i+1,s);
                int len = Math.max(single,dou);
                if(len>r-l+1){
                    l = i-(len-1)/2;
                    r = l + len - 1;
                }
            }
            return s.substring(l,r+1);
        }
        public int longestWithCenter(int s1, int s2, String s){
            while(s1>=0&&s2<s.length()&&s.charAt(s1)==s.charAt(s2)){
                s1--;
                s2++;
            }
            return s2-s1-1;
        }
    

    Nothing special, just implemented by finding each possible substring at its center, which contains center of single point and dou point.


  • 0
    X
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.