Post

Leetcode 0125. Valid Palindrome

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.

Description

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

  • “amanaplanacanalpanama” is a palindrome.

Example 2:

Input: s = “race a car”
Output: false

  • “raceacar” is not a palindrome.

Example 3:

Input: s = “ “
Output: true

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
  /**
   * Two Pointer's
   * Analysis
   * Time Complexity: BigO(n)
   * Space Complexity: BigO(n)
   */
  public boolean isPalindrome(String s) {
    String str = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == str.charAt(str.length()-1-i)) {
        if (i == str.length() - 1 - i) return true;
        continue;
      }
      else return false;
    }
    return true;
  }
}
This post is licensed under CC BY 4.0 by the author.