王廷瑋|數位醫療|智慧醫療: 125. Valid Palindrome WFU

2024年7月6日 星期六

125. Valid Palindrome

125. Valid Palindrome


如果將所有大寫字母轉換為小寫字母並移除所有非字母數字字符後,一個短語從前往後和從後往前讀是一樣的,那麼它就是一個回文。字母數字字符包括字母和數字。

給定一個字符串 s,如果它是回文,則返回 true,否則返回 false。

範例:

輸入:s = "A man, a plan, a canal: Panama" 輸出:true 解釋:"amanaplanacanalpanama" 是一個回文。


Python


class Solution:
def isPalindrome(self, s: str) -> bool:
# Function to filter and convert to lowercase
filtered_chars = [char.lower() for char in s if char.isalnum()]
# Use two pointers to check palindrome
left, right = 0, len(filtered_chars) - 1
while left < right:
if filtered_chars[left] != filtered_chars[right]:
return False
left += 1
right -= 1
return True

21.80MB, 43ms


C++


#include <string>
#include <cctype>
using namespace std;

class Solution {
public:
bool isPalindrome(string s) {
int left = 0;
int right = s.size() - 1;
while (left < right) {
// Move left pointer to the next alphanumeric character
while (left < right && !isalnum(s[left])) {
left++;
}
// Move right pointer to the previous alphanumeric character
while (left < right && !isalnum(s[right])) {
right--;
}
// Compare characters in lower case
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
left++;
right--;
}
return true;
}
};

8.57MB, 4ms


Javascript


/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
// Function to check if a character is alphanumeric
const isAlphanumeric = (char) => {
return /^[a-z0-9]+$/i.test(char);
};
// Initialize two pointers
let left = 0;
let right = s.length - 1;
while (left < right) {
// Move left pointer to the next alphanumeric character
while (left < right && !isAlphanumeric(s[left])) {
left++;
}
// Move right pointer to the previous alphanumeric character
while (left < right && !isAlphanumeric(s[right])) {
right--;
}
// Compare characters in lower case
if (s[left].toLowerCase() !== s[right].toLowerCase()) {
return false;
}
left++;
right--;
}
return true;
};

55.44MB, 62ms