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?
You could try something like this:
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,iandj– my basic rule is that, if you have to resort tojat all, you’re better off naming your counters more expressively (iis okay if it’s the only counter).