Efficient Palindrome judgment Method (Java)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.