My accepted approach without checking odd or even substring and performance improved.


  • 0
    S
    public String longestPalindrome(String s){
    	int len = s.length(), l, r;
    	String res = "";
    	for(int i = 0; i < len; i++){
    		l = r = i;
    		// already got the longest substring
    		if(res.length() > (len - i) * 2){
    			break;
    		}
    		// handling case of repeating chars
    		while(r + 1 < len && s.charAt(l) == s.charAt(r + 1)){
    				r++;
    				i = r;
    		}
    		while(0 <= l && r <= len - 1){
    			if(s.charAt(l) == s.charAt(r)){
    				if(res.length() < r + 1 - l){
    					res = s.substring(l, r + 1);
    				}
    				l--;
    				r++;
    			}
    			else{
    				break;
    			}
    		}
    	}
    	return res;
    }
    

Log in to reply
 

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