LeetCode 125. Valid Palindorme (验证回文字符串)

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

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

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


题目标签:String, Two Pointers

  题目给了我们一个string s, 让我们判断它是不是 palindorme。

  对于s, 我们只需要比较 字母 和 数字。

设置一个 left = 0, right = s.length() -1,依次比较,其中遇到任何其他 char 就跳过,具体看code。

  一开始不知道有 Character.isLetterOrDigit() ,还分别用了 letter 和 digit - -

Java Solution:

Runtime beats 80.01%

完成日期:03/07/2017

关键词:two pointers

关键点:skip all non-alphanumeric chars

 class Solution
{
public boolean isPalindrome(String s)
{
// use two pointers
int left = 0;
int right = s.length() - 1; char [] char_arr = s.toCharArray(); while(left < right)
{
while(left < right && !Character.isLetterOrDigit(char_arr[left])) // if char is not letter or digit
left++; while(left < right && !Character.isLetterOrDigit(char_arr[right])) // if char is not letter or digit
right--; if(Character.toUpperCase(char_arr[left]) != Character.toUpperCase(char_arr[right]))
return false; left++;
right--;
} return true;
} }

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

上一篇:125 Valid Palindrome 验证回文字符串


下一篇:leetcode.双指针.680验证回文字符串-Java