Easy and clear Java solution


  • 5
    B

    The reason I do left =i right =i and left=i right=i+1 is there are two kinds palindromes one is like "abcba" and another is like "abccba".

        int start=0, end=0;
    	int maxLen = 1;
    	for(int i = 0; i < s.length(); i++){
    		int left = i;
    		int right = i;
    		while(left>-1 && right<s.length() && s.charAt(left) == s.charAt(right)){
    			left--;
    			right++;
    		}
    		if(maxLen<right-left+1){
    			maxLen = right - left + 1;
    			start = left+1;
    			end = right-1;
    		}
    		left = i;
    		right = i+1;
    		while(left>-1 && right<s.length() && s.charAt(left) == s.charAt(right)){
    			left--;
    			right++;
    		}
    		if(maxLen<right-left+1){
    			maxLen = right - left + 1;
    			start = left+1;
    			end = right-1;
    		}
    		
    	}
    	return s.substring(start,end+1);

  • 2
    G

    your code is great.

    But I found an error when calculating maxLen.

    if should be

    maxLen < right-left-1


  • 0
    B

    Let's say input is "qweabccbaiop", so the longest panlidrome is "abccba" whose start index is 3, end index is 8 and length is 6, therefore, length = right-left+1.

    Happy Thanksgiving day.


  • 0
    G

    when you found "abccba", the left is actually pointing at "e", and right is pointing "i", that's why I suggest "right-left-1". I ran your code in eclipse, and it showed what i said here.

    Thanks for the quick reply and Happy Thanksgiving!


  • 0
    B

    haha, you are right. It got AC so I did not test in Eclipse, thanks for pointing out error


  • 0
    Y

    smart! we just need to keep track of the len, start and end, we don't need to actually generate the substring as an intermediate process.


Log in to reply
 

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