The problem is, given any size string (has to fit in the String class) check to see if it contains a palindrome. We'll define a palindrome as longer than 2 characters. If the string contains a palindrome, print out true, otherwise print out false. I.E. abby -> false, abba -> true, repelevilasaliveleper -> true
This one weas fairly easy. I got caught up initially because I kept wanting to return the palindrome that is found but that's not necessary. Also, we don't care about how long the palindrome is, so we can stop looking after we find the middle three digits of the palindrome.
ReplyDeleteprivate boolean containsPalin(String string) {
char[] chars = string.toCharArray();
for (int i = 1; i < chars.length - 1; i++) {
if (chars[i - 1] == chars[i + 1])
return true;
if (chars[i - 1] == chars[i] && i > 1 && i < chars.length)
if (chars[i - 2] == chars[i + 1])
return true;
}
return false;
}
what does this line do?
ReplyDeleteif (chars[i - 1] == chars[i] && i > 1 && i < chars.length)
I know that it compares two chars AND some conditions, but if that is all true, what happens? It just goes onto the next if statement.
The second if statement there is an imbedded if statement. Because we qualify a palindrome as longer than 3 characters, we can't accept one that is only 2 characters long as valid. That first if statement finds 2 consecutive characters, and ensures we're not on the edge, and if we've found 2 consecutive characters, then we can go on to check the next 2 characters to make sure it's a palindrome. I could've written the second if statement in that first one, but I thought it looked a little sloppy.
DeleteI turned it into one big if statement, and I fixed the edge case (I was checking it wrong but because it never actually got to that point, the i < chars.length was redundant)
Deleteprivate boolean containsPalin(String string) {
char[] chars = string.toCharArray();
for (int i = 1; i < chars.length - 1; i++) {
if (chars[i - 1] == chars[i + 1])
return true;
if (chars[i - 1] == chars[i] && i > 1
&& chars[i - 2] == chars[i + 1])
return true;
}
return false;
}
yeah thats what I was wondering, why it wasnt all one if statement. I think it looks better this way...is that not proper coding style?
DeleteYou're absolutely right. It does look better, I was inconsistent using && and another if, I should've chosen one path or the other.
Delete