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
1 class Solution 2 { 3 public boolean isPalindrome(String s) 4 { 5 // use two pointers 6 int left = 0; 7 int right = s.length() - 1; 8 9 char [] char_arr = s.toCharArray(); 10 11 while(left < right) 12 { 13 while(left < right && !Character.isLetterOrDigit(char_arr[left])) // if char is not letter or digit 14 left++; 15 16 while(left < right && !Character.isLetterOrDigit(char_arr[right])) // if char is not letter or digit 17 right--; 18 19 if(Character.toUpperCase(char_arr[left]) != Character.toUpperCase(char_arr[right])) 20 return false; 21 22 left++; 23 right--; 24 } 25 26 return true; 27 } 28 29 30 }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/