LeetCode 125. Valid Palindrome

原题链接在这里: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 }

AC C++:

 1 class Solution {
 2 public:
 3     bool isPalindrome(string s) {
 4         int l = 0;
 5         int r = s.length() - 1;
 6         while(l < r){
 7             while(l < r && !isalnum(s[l])){
 8                 l++;
 9             }
10 
11             while(l < r && !isalnum(s[r])){
12                 r--;
13             }
14 
15             if(tolower(s[l]) != tolower(s[r])){
16                 return false;
17             }
18 
19             l++;
20             r--;
21         }
22 
23         return true;
24     }
25 };

AC Python:

 1 class Solution:
 2     def isPalindrome(self, s: str) -> bool:
 3         l, r = 0, len(s) - 1
 4         while l < r:
 5             while l < r and not s[l].isalnum():
 6                 l += 1
 7             while l < r and not s[r].isalnum():
 8                 r -= 1
 9             if s[l].lower() != s[r].lower():
10                 return False
11             l += 1
12             r -= 1
13         return True

跟上Valid Palindrome II.

posted @ 2015-12-03 11:27  Dylan_Java_NYC  阅读(209)  评论(0编辑  收藏  举报