Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to determine whether an input string is a palindrome or not

I recently wrote this short method to determine whether a string is a palindrome. I was wondering what I could do to make it more efficient, surely I'm missing simple built-in functions that can speed up the calculation.

Thank you all for your help!

boolean checkPalindrome(String inputString) {

    ArrayList<Character> arrFront = new ArrayList<Character>();
    ArrayList<Character> arrBack = new ArrayList<Character>();

    for(int i=0; i<inputString.length()-1; i++) {
        arrFront.add(inputString.charAt(i));
    }

    for(int i=inputString.length()-1; i>0; i--) {
        arrBack.add(inputString.charAt(i));
    }

    StringBuilder builder1 = new StringBuilder(arrFront.size());
    for (Character c : arrFront) {
        builder1.append(c);
    }
    String front = builder1.toString();

    StringBuilder builder2 = new StringBuilder(arrBack.size());
    for (Character c : arrBack) {
        builder2.append(c);
    }
    String back = builder2.toString();

    return(front.equals(back));
}

1 Answers

In terms of efficiency, it is not always about built-in functions and using libraries (although in many cases they are the best choice). But sometimes a simple loop like this could be the most simple and efficient way:

private boolean checkPalindrome(String inputString) {
    for(int i = 0, j = inputString.length() - 1; i < j; i++, j--) {
        if(inputString.charAt(i) != inputString.charAt(j)) {
            return false;
        }
    }
    return true;
}
like image 53
Mohamed Elsayed Avatar answered Feb 03 '26 03:02

Mohamed Elsayed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!