Today I was fortunate to see a few of the articles on Palindrome, are written in different languages, useful recursive algorithm, but also useful circulation, but I think are not very efficient.
In the process of parameter passing, the recursive algorithm produces a large number of new objects, which is bad for memory because of the Java language.
There are many uses of the loop, but the design has problems, speed is not very fast, all I have written according to the characteristics of the Java language, only for reference, please advise.
public boolean ispalindrome (char[] text) {
Boolean flag = true;
int i = 0;
int textlen = 0;
if (null!= text) {
Textlen = Text.length;
}else{
return false;
}
int middle = (textLen-1)/2;
for (i = 0; I <= Middle; i++) {
if (Text[i]!= text[textlen-i-1]) {
Flag = false;
break;
}
}
return flag;
}
Why say is efficient, please listen to my detailed:
The number of cycles is determined by middle, not (TEXT.LENGH-1/2), so that every cycle is recalculated, because each cycle is to recalculate the conditional constraints, to be judged again. If you use i<=textlen-i-1 as a criterion, the speed may be more than one times slower.
Second entrance an outlet, conforms to the software engineering structural design idea.
Third, in the case of Text==null will not continue to judge, can prevent null pointer error.
Four, the initial is set Flag=true, rather than false, reduced a lot of complex judgments, do not believe that we can flag=false the initial conditions to try, a certain number of locks.