recursion - understanding compareto() method in java -
i came across mit lecture on recursion checked palindrome using recursion,and there checked using logic compare first , last alphabet , on.. thought follows
just pseudo code:
string original="abba"; string reverse = ""; for(int i=original.length()-1;i>=0;i--) { reverse+=new string(original.substring(i,i+1)); } if(original.equals(reverse)) system.out.println("palindrome"); else system.out.println("not palindrome");
i have 2 doubts
- is logic better recursion or conventional logic in terms of time complexity?
- how
compareto()
method checks if strings equal? compare bytecode or something?
you should use equals
, not compareto
, since compareto returns int , not boolean if
condition expect. alternately can check if (original.compareto(reverse)==0)
, means strings equal.
as how compareto works, compares each pair of characters having same index, , returns difference between first non equal pair. if equal, 0 returned.
Comments
Post a Comment