标签:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
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.
"A man, a plan, a canal: Panama"
is a palindrome.
"race a car"
is not a palindrome.
分析:
两个指针指向前后两端,如果指向的值不是alphanumeric characters,向前/后走。
1 public class Solution { 2 /** 3 * @param s A string 4 * @return Whether the string is a valid palindrome 5 */ 6 public boolean isPalindrome(String s) { 7 if(s == null || s.length() <= 1) return true; 8 9 int i = 0; 10 int j = s.length() - 1; 11 12 s = s.toLowerCase(); 13 14 while (i < j) { 15 while(i < s.length() && !(s.charAt(i) <= ‘Z‘ && s.charAt(i) >= ‘A‘ || s.charAt(i) <= ‘z‘ && s.charAt(i) >= ‘a‘ || s.charAt(i) <= ‘9‘ && s.charAt(i) >= ‘0‘)) { 16 i++; 17 } 18 while(j >= 0 && !(s.charAt(j) <= ‘Z‘ && s.charAt(j) >= ‘A‘ || s.charAt(j) <= ‘z‘ && s.charAt(j) >= ‘a‘ || s.charAt(j) <= ‘9‘ && s.charAt(j) >= ‘0‘)) { 19 j--; 20 } 21 22 if (i < j) { 23 if (s.charAt(i) == s.charAt(j)) { 24 i++; 25 j--; 26 } else { 27 return false; 28 } 29 } 30 } 31 return true; 32 } 33 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5658775.html