简体   繁体   中英

Longest Palindromic Substring using expandfromcenter approach

I am trying to do Leetcode Longest Palindromic Substring with expandfromCentre approach, but instead of returning the length in the function as most of the solutions did, I tried returning the string itself. I think it should work... I don't know what's causing the error.

class Solution {
    public String longestPalindrome(String s) {
        int n = s.length();
        int maxLength = 1;
        
        String res = Character.toString(s.charAt(0));
        
        int start=0; int end=0;
        
        for(int i=0; i<n; i++){
            String s1 = expandFromCentre(s, i, i); // aba            
            String s2 = expandFromCentre(s, i, i+1);  //abba
            
            if(s1.length()>=s2.length()){
                res = s1;
            }
            else{
                res = s2;
            }
        
        }                
        return res;
        
    }
    
    static String expandFromCentre(String s, int left, int right){
        int n = s.length();
        
        while(left>=0 && right<n && s.charAt(left)==s.charAt(right) ){
            left--;
            right++;
        }
   
        return s.substring(left+1, right);
        
    }
}

Issue:

if(s1.length()>=s2.length()){
   res = s1;
}else{
   res = s2;
}

Issue is with the above snippet. You assign either of the value to res regardless of whether it will give you the longest palindrome candidate or not. In other words, you are overwriting res each time without having additional checks for it's length since we need to find the longest .

Solution:

You can do the below to fix it:

public String longestPalindrome(String s) {        
    String res = "";    
    for(int i = 0; i < s.length(); i++){
        String s1 = expandFromCentre(s, i, i); // aba            
        String s2 = expandFromCentre(s, i, i+1);  //abba
        
        if(res.length() < s1.length()){
            res = s1;
        }
        
        if(res.length() < s2.length()){
            res = s2;
        }        
    }                
    return res;        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM