125. Valid Palindrome
https://leetcode.com/problems/valid-palindrome/description/
Last updated
Was this helpful?
https://leetcode.com/problems/valid-palindrome/description/
Last updated
Was this helpful?
Was this helpful?
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
忽略所有非数字和字母,检查给定str是否回文。要检查首尾配对是否相同,用首尾两个指针同时走,当遇到非数字和字母就让指针先走。
/*
* @lc app=leetcode id=125 lang=cpp
*
* [125] Valid Palindrome
*/
// @lc code=start
class Solution {
public:
bool isPalindrome(string s) {
for (
class Solution {
public boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
char cl = s.charAt(l);
char cr = s.charAt(r);
if (!Character.isLetterOrDigit(cl)) {
l++;
} else if (!Character.isLetterOrDigit(cr)) {
r--;
} else if (Character.toLowerCase(cl) == Character.toLowerCase(cr)) {
l++;
r--;
} else {
return false;
}
}
return true;
}
}
Errors:
把数字也当作需要忽略的字符了。
时间复杂度O(n).