Time complexity O() of isPalindrome()

Posted by Aran on Stack Overflow See other posts from Stack Overflow or by Aran
Published on 2009-08-23T13:27:59Z Indexed on 2012/12/02 11:05 UTC
Read the original article Hit count: 237

I have this method, isPalindrome(), and I am trying to find the time complexity of it, and also rewrite the code more efficiently.

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

Now I know this code checks the string's characters to see whether it is the same as the one before it and if it is then it doesn't change bP.

And I think I know that the operations are s.length(), s.charAt(i) and s.charAt(s.length()-i-!)).

Making the time-complexity O(N + 3), I think? This correct, if not what is it and how is that figured out.

Also to make this more efficient, would it be good to store the character in temporary strings?

© Stack Overflow or respective owner

Related posts about java

Related posts about Performance