I am solving the 125. Valid Palindrome problem in leetcode. For testcase
A man, a plan, a canal: Panama
with below code, it is returning false:
class Solution {
public boolean isPalindrome(String s) {
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if ((curr <= 57 && curr >= 48) || (curr >= 97 && curr <= 122) || (curr <= 90 && curr >= 65)) {
curr = Character.toLowerCase(curr);
s1.append(curr);
}
}
s2.append(s1);
s2.reverse();
if (s2.equals(s1)) {
return true;
}
return false;
}
}
This part of your code is the problem:
What you are doing here is comparing two
StringBuilderobjects, and they are obviously always different. What you should to instead is to compare theStrings that are build using those builders. To get the string from the builder you need to usetoStringmethod. So, your code should look like that:I've tested your code with this change and it works correctly now. I hope it helps.