Valid Palindrome

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 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.

Solution

This is a classic problem that uses a stack as the solution. Who hasn’t written such an algorithm?

O(n) time, O(n) space.

There is an O(1) space algorithm that doesn’t use a stack. You could use two pointers to check.

class Solution {
    public boolean isPalindrome(String s) {
        s = s.toLowerCase();
        var stack = new Stack<Character>();

        for (var c : s.toCharArray()) {
            var i = (int) c;
            if ((i >= 97 && i <= 122) || (i >= 48) && (i <= 57)) {
                stack.push(c);
            }
        }

        for (var c : s.toCharArray()) {
            var i = (int) c;
            if ((i >= 97 && i <= 122) || (i >= 48) && (i <= 57)) {
                var result = stack.pop();
                if (!result.equals(c)) {
                    return false;
                }
            }
        }

        return true;
    }
}

Recent posts from blogs that I like

Paintings of Saint-Tropez: Colour, boats and bathers 2

Paintings by Paul Signac, Maximilien Luce, and Pierre Bonnard showing fishing boats, trees and bathers near this smalll fishing village on the Mediterranean coast.

via The Eclectic Light Company

Run LLMs on macOS using llm-mlx and Apple's MLX framework

via Simon Willison

How to add a directory to your PATH

I was talking to a friend about how to add a directory to your PATH today. It’s something that feels “obvious” to me since I’ve been using the terminal for a long time, but when I searched for instructions for how to do it, I actually couldn’t find something that explained all of the steps – a lot o...

via Julia Evans