https://leetcode.com/problems/valid-palindrome/description/
a pretty easy sol that I dafuq retried many times cuz I tried splitting the string that I built like
public boolean isPalindrome(String s) {
StringBuilder sb = new StringBuilder();
for(char c:s.toCharArray()){
if((c>='a'&&c<='z') || (c>='A'&&c<='Z')){
sb.append(Character.toLowerCase(c));
}
}
int length=sb.length()/2;
int remainder = sb.length()%2;
System.out.println(length);
System.out.println(sb.toString());
for(int i=0;i<length;i++){
char c = sb.charAt(length - 1 - i);
if(sb.charAt(i)!=sb.charAt(length-1-i)) return false;
}
return true;
}
But look at sb.charAt(length-1-i). IT looks right but is wrong. Cuz length i declared as half the actual length. So actually Im just comparing half the original string, which is wrong.
Also there can be numbers too so i cant just take characters.
we can use
Character.isLetterOrDigit() to check if is alphabet or num and
Character.toLowerCase()
class Solution {
public boolean isPalindrome(String s) {
int left=0;int right=s.length()-1;
while(left<=right){
char cl=s.charAt(left);
char cr=s.charAt(right);
if(!Character.isLetterOrDigit(cl)) left+=1;
else if (!Character.isLetterOrDigit(cr)) right-=1;
else{
if(Character.toLowerCase(cl)!=Character.toLowerCase(cr)) return false;
left+=1;
right-=1;
}
}
return true;
}
}
n time
1 space