详细见:leetcode.com/problems/valid-palindrome
Java Solution: github
package leetcode;
/*
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.
*/
/**
* @author zxwtry
* @email zxwtry@qq.com
* @project OJ
* @package leetcode
* @file P125_ValidPalindrome.java
* @type P125_ValidPalindrome
* @date 2017年5月7日 下午9:53:18
* @details Solution: AC 5ms 97.89%
*/
public class P125_ValidPalindrome {
static class Solution {
private char get(String s, int i) {
char c = s.charAt(i);
if (c >= 'A' && c <= 'Z') c -= 'A'-'a';
return c;
}
private boolean cmp(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z');
}
public boolean isPalindrome(String s) {
int i = 0, j = s == null ? -1 : s.length()-1;
while (i < j) {
char l = get(s, i);
if (! cmp(l)) {
i ++;
} else {
char r = get(s, j);
if (! cmp(r)) {
j --;
} else if (l == r) {
i ++;
j --;
} else return false;
}
}
return true;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/valid-palindrome
AC 3ms 55.29%
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define bool int
int cmp(char a, char b) {
if (a >= 'A' && a <= 'Z') a = (char)(a - 'A' + 'a');
if (b >= 'A' && b <= 'Z') b = (char)(b - 'A' + 'a');
if (!((a >= 'a' && a <= 'z') || (a >= '0' && a <= '9'))) return INT_MIN;
if (!((b >= 'a' && b <= 'z') || (b >= '0' && b <= '9'))) return INT_MAX;
return a - b;
}
bool isPalindrome(char* s) {
int l = 0, r = (s==NULL?0:strlen(s))-1, j = 0;
while (l < r) {
j = cmp(s[l], s[r]);
if (j == INT_MIN) l ++;
else if (j == INT_MAX) r --;
else if (j != 0) return 0;
else {
l ++;
r --;
}
}
return 1;
}
int main() {
char* s = "0P";
printf("answer is %d\n", isPalindrome(s));
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/valid-palindrome
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年5月5日
@details: Solution: 136ms 16.05%
'''
class Solution(object):
def ord_val(self, v):
return (v >= 97 and v <= 122) or (v >= 48 and v <= 57)
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
i, j = 0, len(s)-1
while i < j:
left = ord(s[i])
if self.ord_val(left):
right = ord(s[j])
if self.ord_val(right):
if left != right: return False
i, j = i+1, j-1
else: j -= 1
else: i += 1
return True
if __name__ == "__main__":
ss = ["A man, a plan, a canal: Panama", "race a car"]
for s in ss:
print(Solution().isPalindrome(s))