177.Valid Palindrome
题目:
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: true
Example 2:
Input: "race a car" Output: false
解答:
方法一:
1 class Solution { 2 public boolean isPalindrome(String s) { 3 if(s.length()==0) return true; 4 5 int head=0,tail=s.length()-1; 6 while(head<tail){ 7 if(!isAlphaNumeric(s.charAt(head))) 8 head++; 9 else if(!isAlphaNumeric(s.charAt(tail))) 10 tail--; 11 else{ 12 if(Character.toLowerCase(s.charAt(head))!=Character.toLowerCase(s.charAt(tail))) 13 return false; 14 head++; 15 tail--; 16 } 17 } 18 return true; 19 } 20 21 private boolean isAlphaNumeric(Character c){ 22 if(c>='a'&& c<='z') return true; 23 else if(c>='A' && c<='Z') return true; 24 else if(c>='0' && c<='9') return true; 25 return false; 26 } 27 }
方法二:用自带的Character.isLetterOrDigit判断
1 class Solution { 2 public boolean isPalindrome(String s) { 3 if(s.length()==0) return true; 4 5 int head=0,tail=s.length()-1; 6 while(head<tail){ 7 if(!Character.isLetterOrDigit(s.charAt(head))) 8 head++; 9 else if(!Character.isLetterOrDigit(s.charAt(tail))) 10 tail--; 11 else{ 12 if(Character.toLowerCase(s.charAt(head))!=Character.toLowerCase(s.charAt(tail))) 13 return false; 14 head++; 15 tail--; 16 } 17 } 18 return true; 19 } 20 }
详解:
思路:设置head和tail指针,遇到非字母数字字符则跳过,转换成小写字母两两比较是否相等