标签:
原题链接在这里:https://leetcode.com/problems/valid-palindrome/
注意在用Character.isLetter(s.charAt(i)) 或者 Character.isDigit(s.charAt(i))前需检验 i 是否index out of bound 了。
Time Complexity: O(n), n = s.length(). Space: O(1).
AC Java:
public class Solution { public boolean isPalindrome(String s) { if(s == null || s.length() == 0){ return true; } s = s.trim().toLowerCase(); int l = 0; int r = s.length()-1; while(l < r){ while(l <= s.length()-1 && !Character.isLetter(s.charAt(l)) && !Character.isDigit(s.charAt(l))){ l++; } while(r >= 0 && !Character.isLetter(s.charAt(r)) && !Character.isDigit(s.charAt(r))){ r--; } if(l <= s.length()-1 && r >= 0 && s.charAt(l) != s.charAt(r)){ return false; } l++; r--; } return true; } }
LeetCode https://leetcode.com/problems/valid-palindrome/
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5015593.html