原题链接在这里:https://leetcode.com/problems/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
题解:
注意在用Character.isLetterOrDigit(s.charAt(i)) 前需检验 i 是否index out of bound 了.
Note: if first check i < j.
Time Complexity: O(n), n = s.length().
Space: O(1).
AC Java:
1 class Solution { 2 public boolean isPalindrome(String s) { 3 if(s == null || s.length() == 0){ 4 return true; 5 } 6 7 int i = 0; 8 int j = s.length() - 1; 9 while(i < j){ 10 while(i < j && !Character.isLetterOrDigit(s.charAt(i))){ 11 i++; 12 } 13 14 while(i < j && !Character.isLetterOrDigit(s.charAt(j))){ 15 j--; 16 } 17 18 if(i < j && Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))){ 19 return false; 20 } 21 22 i++; 23 j--; 24 } 25 26 return true; 27 } 28 }