🎀 The Problem
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
👩💻 My Answer
class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
int i = 0;
int j = s.length() - 1;
while (i != j && i < s.length()) {
while (48 > s.charAt(i) || (57 < s.charAt(i) && s.charAt(i) < 97) || s.charAt(i) > 122) {
i++;
if (i == s.length())
return true;
}
while (48 > s.charAt(j) || (57 < s.charAt(j) && s.charAt(j) < 97) || s.charAt(j) > 122) {
j--;
}
if (s.charAt(j) != s.charAt(i))
return false;
i++;
j--;
}
return true;
}
}
Pro & Con
- ✖️ Runtime & Memory
- ✖️ Too long
- ✖️ Bit complicated (Hard to read)
💋 Ideal Answer
Approach
I read the solution post on LeetCode and realized there is a library to check if the char is a letter (Character.isLetterOrDigit()
)
New Code
class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
int i = 0;
int j = s.length() - 1;
while (i < j) {
if (!Character.isLetterOrDigit(s.charAt(i))) {
i++;
} else if (!Character.isLetterOrDigit(s.charAt(j))) {
j--;
} else if (s.charAt(j) != s.charAt(i))
return false;
else {
i++;
j--;
}
}
return true;
}
}
It does not beat 100%, but this was the most efficient java solution that I found.
💡 What I Learned
How to detect if it's a letter or not
Character.isLetterOrDigit(CHAR_NAME)
How to make string to lower character
STRING_NAME.toLowerCase()
Top comments (0)