[leetcode]Valid Palindrome

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:首尾两指针,在原来的字符串的基础上,进行扫描判断。空间复杂度O(1),时间O(n),一次扫描。

 1 public class Solution {
 2       public boolean isPalindrome(String s) {
 3         s = s.trim().toLowerCase();
 4         int i = 0;
 5         int j = s.length() - 1;
 6         while(i < s.length() && !isValid(s.charAt(i))) i++;
 7         while(j >= 0 && !isValid(s.charAt(j))) j--;
 8         while(i <= j){
 9             char a = s.charAt(i);
10             char b = s.charAt(j);
11             if(a != b){
12                 return false;
13             }else{
14                 i++;
15                 while(i < s.length() && !isValid(s.charAt(i))) i++;
16                 j--;
17                 while(j >= 0 && !isValid(s.charAt(j))) j--;
18             }
19         }
20         return true;
21     }
22     private boolean isValid(char c){
23         if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ) return true;
24         return false;
25     }
26 }

 

思路2:第一遍扫描,将合法字符保留在另一个字符串s中,第二遍扫描s。空间复杂度O(1),时间复杂度O(n),两次扫描。

比较简单,不实现了

posted on 2014-07-25 15:47  喵星人与汪星人  阅读(163)  评论(0编辑  收藏  举报