博文中会简要介绍Leetcode P0125题目分析及解题思路。
“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.
以下是Java的题解代码实现。
class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
int len = s.length();
int left = 0, right = len-1;
while (left < right) {
char leftCh = Character.toLowerCase(s.charAt(left));
char rightCh = Character.toLowerCase(s.charAt(right));
boolean lf = (leftCh >= 'a' && leftCh <= 'z') || (leftCh >= '0' && leftCh <= '9' );
boolean rf = (rightCh >= 'a' && rightCh <= 'z') || (rightCh >= '0' && rightCh <= '9' );
if (lf && rf) {
if (leftCh != rightCh)
return false;
++left;
--right;
}
else {
left += lf? 0: 1;
right -= rf? 0: 1;
}
}
return true;
}
}
以下是C++的题解代码实现。
class Solution {
public:
bool isPalindrome(string s) {
int len = s.length();
int left = 0, right = len-1;
while (left < right) {
char left_ch = tolower(s[left]);
char right_ch = tolower(s[right]);
bool lf = (left_ch >= 'a' && left_ch <= 'z') || (left_ch >= '0' && left_ch <= '9' );
bool rf = (right_ch >= 'a' && right_ch <= 'z') || (right_ch >= '0' && right_ch <= '9' );
if (lf && rf) {
if (left_ch != right_ch)
return false;
++left;
--right;
}
else {
left += lf? 0: 1;
right -= rf? 0: 1;
}
}
return true;
}
};