Reputation: 509
I have the following code:
int t = s.length()-1;
int g = 0;
for (int i=0; i < s.length(); i++){
if (s.charAt(i) != h.charAt(t--));
g++;
}
if (g==0)
return true;
else
return false;
Basically what this code is suppose to do is to test if string h's inverse is equal to string s, or vice versa. For some reason a "false" is always returned - although the obvious answer is true.
Can anyone please tell me what's wrong with my code?
Thanks!
Upvotes: 3
Views: 1111
Reputation: 28755
extra ;
in if (s.charAt(i) != h.charAt(t--));
may create the issue
Use
if (s.charAt(i) != h.charAt(t--))
{
g++;
break; // if not match, not need to continue with loop
}
Upvotes: 3
Reputation: 9498
Unless this is a learning exercise, I'd recommend you avoid writing the loops yourself and use some library code. You can do:
String s = "abcd";
String h = "dcba";
System.out.println( h.equals( new StringBuffer(s).reverse().toString() ) );
Under the hood, these loop through the string in much the same way that you were doing. The code is in AbstractStringBuilder, if you'd like to take a look.
Upvotes: 1
Reputation: 15344
use break;
to come out of the loop if it don't have same char
bool g = true;
for(.....)
{
if (s.charAt(i) != h.charAt(t--))
{
g = false;
break;
}
}
return g;
It increases your performance
Upvotes: 0
Reputation: 47183
I'd say an extra ;
is the culprit.
Instead of
if (s.charAt(i) != h.charAt(t--));
use
if (s.charAt(i) != h.charAt(t--))
You should always go the "safe" route. That is, use braces after if-else statements (and pretty much everywhere you can use them), so bugs like this won't happen in the first place. The correct way to write it is:
if (s.charAt(i) != h.charAt(t--)) {
g++;
}
And by the way, your code will blow up if you don't check first that s
and h
have the same length.
Upvotes: 8