Eassiest java Code with O(n^2) without DP


#1

public class Solution {

private static int expandFromMiddle(String A, int left, int right){
    if(A.length() == 0 || left > right) return 0;
    
    while (left >=0 && right < A.length() && A.charAt(left) == A.charAt(right)) {
            left--;
            right++;
    }
    
    return right-left-1;
}
public String longestPalindrome(String A) {
    if(A == null || A.length() < 1) return "";
    int start = 0 ;
    int end = 0;
    int maxLen = 0;
    for (int i = 0 ; i < A.length(); i++) {
        int len1 = expandFromMiddle(A,i,i);
        int len2 = expandFromMiddle(A,i,i+1);
        if(maxLen < Math.max(len1,len2)){
            int len = Math.max(len1,len2);
            if(len > end - start){
                start = i - (len-1)/2;
                end = i + (len)/2;
            }
            maxLen = len;
        }
    }

    return A.substring(start,end+1);
}

}