Valid Palindrome

Question

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

Notice

Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

Example

"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.

Challenge

O(n) time without extra memory.

Tags

String Two Pointers Facebook Zenefits Uber

Related Problems

Medium Palindrome Linked List Medium Longest Palindromic Substring

Analysis

根据Palindrome本身对称性的特点,比较适合用two pointers的方法来解决,因为这里对valid palindrome的定义不考虑非字母和数字的字符,就需要在移动pointers时候注意条件判断,除了下标的边界,还有isAlphanumeric()来判定是否为字母和数字。isAlphanumeric()可以用内置函数Character.isLetter()Character.isDigit(),也可以根据char ASCII码的定义写出。补充:还有一个专门内置函数:Character.isLetterOrDigit(),用Character.toLowerCase()统一大小写。

Test Cases需要考虑周到,比如:

" " "a..." "...a" "a.a"

Solution

Another implementation of isAlphanumeric()

A verbose way - filter alphanumeric first, then start expanding from middle point of the new string

Time - O(n), Space O(n)

*(Preferred) A concise, one pass (4ms, 92.32%)

善用Character.isLetterOrDigit()函数,跳过非alphanumeric的字符,然后在比较时,用Character.toLowerCase()统一大小写。

Reference

http://www.jiuzhang.com/solutions/valid-palindrome/

Last updated

Was this helpful?