Skip to content

Instantly share code, notes, and snippets.

@rungxanh1995
Last active May 3, 2022 17:21
Show Gist options
  • Save rungxanh1995/896b40c63995f1b49ceb4dca2cee884e to your computer and use it in GitHub Desktop.
Save rungxanh1995/896b40c63995f1b49ceb4dca2cee884e to your computer and use it in GitHub Desktop.

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 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

  • 1 <= s.length <= 2 * 10^5
  • s consists only of printable ASCII characters.
class Solution {
public boolean isPalindrome(String s) {
if (s.length() == 0) return true;
StringBuilder filtered = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (Character.isLetterOrDigit(s.charAt(i)))
filtered.append(s.charAt(i));
}
return filtered.toString().equalsIgnoreCase(filtered.reverse().toString());
}
}
class Solution {
fun isPalindrome(s: String): Boolean {
if (s.isEmpty()) { return true }
val filtered = StringBuilder()
for (i in s.indices) {
if (Character.isLetterOrDigit(s[i])) { filtered.append(s[i]) }
}
return filtered.reversed().toString().equals(filtered.toString(), ignoreCase = true)
}
}
# Solution with O(n) space complexity, O(n) time complexity
class Solution:
def isPalindrome(self, s: str) -> bool:
# filter input string into new string with lowercase alphanumbericals
cleaned_s = "".join(e.lower() for e in s if e.isalnum())
# iterate backwards and compare
return cleaned_s[::] == cleaned_s[::-1]
# Solution using left & right pointers, with O(1) space complexity, O(logn) time complexity
class Solution:
def isPalindromeWithPointers(s: str) -> bool:
pointer_left, pointer_right = 0, len(s) - 1
while pointer_left < pointer_right:
# constant checks to ensure left not surpass right pointer
while pointer_left < pointer_right and not s[pointer_left].isalnum():
pointer_left += 1
while pointer_left < pointer_right and not s[pointer_right].isalnum():
pointer_right -= 1
# compare
if s[pointer_left].lower() != s[pointer_right].lower():
return False
# update pointers
pointer_left, pointer_right = pointer_left + 1, pointer_right - 1
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment