Valid Palindrome

描述

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,

"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome.

Note: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.

分析

代码

  1. // Valid Palindrome
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public boolean isPalindrome(String s) {
  5. s = s.toLowerCase();
  6. int left = 0;
  7. int right = s.length() - 1;
  8. while (left < right) {
  9. if (!Character.isLetterOrDigit(s.charAt(left))) ++left;
  10. else if (!Character.isLetterOrDigit(s.charAt(right))) --right;
  11. else if (s.charAt(left) != s.charAt(right)) return false;
  12. else { ++left; --right; }
  13. }
  14. return true;
  15. }
  16. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/string/valid-palindrome.html