【Leetcode】Valid Palindrome

来源:互联网 发布:淘宝图片上传尺寸 编辑:程序博客网 时间:2024/06/13 21:39

题目链接:https://leetcode.com/problems/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.

算法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public boolean isDecent(char c) {  
  2.         if (Character.isAlphabetic(c) || Character.isDigit(c)) {  
  3.             return true;  
  4.         } else  
  5.             return false;  
  6.     }  
  7.   
  8.     public boolean isPalindrome(String s) {  
  9.         char c[] = s.toLowerCase().toCharArray();  
  10.         int i = 0, j = c.length - 1;  
  11.         while (i < j) {  
  12.             if (isDecent(c[i]) && isDecent(c[j])) {  
  13.                 if (c[i] == c[j]) {  
  14.                     i++;  
  15.                     j--;  
  16.                 } else {  
  17.                     return false;  
  18.                 }  
  19.             }  
  20.             if (!isDecent(c[i])) {  
  21.                 i++;  
  22.             }  
  23.             if (!isDecent(c[j])) {  
  24.                 j--;  
  25.             }  
  26.         }  
  27.         return true;  
  28.     }  


1 0