Search code examples
javatime-complexitypalindrome

Decrease the complexity of isPalindrome solution?


Here is my isPalindrome method

public static boolean isPalindrome(String s){
    for(int i = 0; i < s.length()/2; i++){
        int j = s.length() - 1 - i;
        if(s.charAt(i) != s.charAt(j))
            return false;
    }
    return true;
}

my teacher says I can decrease the complexity, but I can't see how. I already am only going through half of the string. Is there any way to decrease the complexity of this solution?


Solution

  • You could try something like this:

    public static boolean isPalindrome (String str) {
        int left = 0;
        int right = str.length() - 1;
    
        while (left < right) {
            if (str.charAt(left) != str.charAt(right))
                return false;
            left++;
            right--;
        }
        return true;
    }
    

    This has the advantage of not calculating the right hand index each time through the loop, especially since it has to access the string length each time (which is constant).

    As an aside, I also tend to prefer more meaningful variable names than s, i and j - my basic rule is that, if you have to resort to j at all, you're better off naming your counters more expressively (i is okay if it's the only counter).