albertonline· portal
blind75

Valid Palindrome: Checking Symmetry in Strings

Jan 14, 2024 · Exploring the solution to determine if a given string is a palindrome, meaning it reads the same forward and backward.

The "Valid Palindrome" problem focuses on determining whether a given string is a palindrome. A palindrome is a sequence of characters that reads the same forward and backward, typically ignoring spaces, punctuation, and capitalization.

Problem Statement

Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Example

  • Input: "A man, a plan, a canal: Panama"
  • Output: true
  • Input: "race a car"
  • Output: false

Solution Approach - Two Pointers Technique (typescript)

typescript

Breaking Down the Solution


  • Preprocessing: Remove all non-alphanumeric characters and convert to lowercase to standardize the string.
  • Two Pointers: Use two pointers, one at the start and one at the end, moving towards the center.
  • Compare Characters: If characters at the start and end pointers don't match, it's not a palindrome.
  • Iterate and Validate: Continue moving pointers inward and comparing until they meet or a mismatch is found.

Conclusion


The Valid Palindrome problem is a classic example of using the two pointers technique to check for symmetry in strings. It's a fundamental exercise in string manipulation and pattern recognition.

Rust Solution

rust

The iterator chain s.chars().filter(|c| c.is_alphanumeric()).map(|c| c.to_ascii_lowercase() as u8).collect() cleans and normalises the string in a single pass, and the explicit Vec<u8> annotation is what tells collect which container to build. Casting each char to u8 means the pointers walk raw bytes, so filtered[l as usize] is a plain O(1) index rather than a UTF-8 decode. Note filtered.len() as isize - 1: widening to isize lets r hold -1 on empty input, sidestepping the panic a bare usize subtraction would trigger, and the as usize casts convert the pointers back at each index. The trailing bare true is the return value — no return keyword needed.

Go Solution

go

strings.Builder accumulates the kept characters via b.WriteRune(c) without the repeated allocations that += string concatenation would incur, and for _, c := range s walks the string as runes. The character-class test is hand-rolled ASCII range comparisons (c >= 'a' && c <= 'z', …) and lowercasing is arithmetic — c += 32 — rather than a stdlib helper. After b.String(), indexing f[l] reads a single byte, so the two-pointer loop compares byte values directly. As with the other solutions, a bare return true closes the happy path.

Comments (0)

Stub comments live in your browser only (localStorage). No server round-trip yet.

No comments yet. Be the first.