Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: trueExample 2:
Input: "race a car" Output: false
有效的回文。题意很简单,验证给的input是否是一个有效的回文。思路也很简单,two pointer逼近。注意
- 只比较input里面的字母和数字
- 需要ignore大小写
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {string} s 3 * @return {boolean} 4 */ 5 var isPalindrome = function (s) { 6 if (s === null || s.length === 0) return true; 7 const alphanum = s.toLowerCase().replace(/[W]/g, ""); 8 let left = 0; 9 let right = alphanum.length - 1; 10 while (left < right) { 11 if (alphanum[left] !== alphanum[right]) { 12 return false; 13 } 14 left++; 15 right--; 16 } 17 return true; 18 };
Java实现
1 class Solution { 2 public boolean isPalindrome(String s) { 3 // corner case 4 if (s == null || s.length() == 0) { 5 return true; 6 } 7 8 // normal case 9 int left = 0; 10 int right = s.length() - 1; 11 while (left < right) { 12 while (left < right && !Character.isLetterOrDigit(s.charAt(left))) { 13 left++; 14 } 15 while (left < right && !Character.isLetterOrDigit(s.charAt(right))) { 16 right--; 17 } 18 if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { 19 return false; 20 } 21 left++; 22 right--; 23 } 24 return true; 25 } 26 }
相关题目