Jump to content

More efficiently algorithm...

- - - - -

  • Please log in to reply
4 replies to this topic

#1
toto_7

toto_7

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 295 posts
Hello,

How i can make the algorithm below more efficiently?

boolean isP(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;

}

I thought insert a
break;
exaclty after
bP=false;
, to terminate the algorithm, there is any better solution?
Thank you

"Programming is like sex. One mistake and you have to support it for the rest of your life."

-Michael Sinz

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
What about this:
boolean isP(String s){
     boolean bP = true;
    for(int i=0; i<(s.length()/2) && bP; i++){
       if(s.charAt(i)!=s.charAt(s.length()-i-1)){
          bP=false;
       }
    }
    return bP;
 }

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
toto_7

toto_7

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 295 posts
An explanation on this please??

Thank you

"Programming is like sex. One mistake and you have to support it for the rest of your life."

-Michael Sinz

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
First, since you're testing for palindromeness, you only have to go half-way through the string, as you've already compared the second half to the first half.
Second, as soon as you find a failure, the loop condition will now fail, breaking the loop.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
toto_7

toto_7

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 295 posts
Ok, now its clear, thank you

"Programming is like sex. One mistake and you have to support it for the rest of your life."

-Michael Sinz




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users