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 the Franco-Prussian War: 2 The Siege of Paris

As winter grew colder, Parisians started to starve. A city known for its food and restaurants had to scavenge meals based on horse, dog, cat and even rat.

via The Eclectic Light Company

Impromptu disaster recovery

via fasterthanlime

Notes on implementing Attention

Some notes on implementing attention blocks in pure Python + Numpy. The focus here is on the exact implementation in code, explaining all the shapes throughout the process. The motivation for why attention works is not covered here - there are plenty of excellent online resources explaining it. Seve...

via Eli Bendersky