November 19, 2023

Viiisit [LeetCode] - 125. Valid Palindrome

#php#javascript#ruby

keep learning, keep coding!

Problem - Valid Palindrome

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

翻譯蒟蒻

給定一個字串,將所有大寫字母轉換為小寫字母並刪除所有非字母數字符號後,字串正向讀和反向讀是一樣的,就返回 true,否則 false。 (補充:palindrome n. 回文(正向讀和反向讀是一樣的))


Solution - JavaScript

Solution 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
// 先用 regex 將所有非字母的字元取代並轉為小寫
let filteredString = s.replace(/[^a-zA-Z\d]/g, "").toLowerCase();

let first = 0;
let last = filteredString.length - 1;

while (first < last) {
if (filteredString[first] !== filteredString[last]) {
return false;
}

first++;
last--;
};

return true;
};

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
let filteredString = s.replace(/[^a-zA-Z\d]/g, "").toLowerCase();

// 直接將過濾後的字串反轉
let reversedString = filteredString.split('').reverse().join('');

return filteredString === reversedString;
};

Solution - Ruby

1
2
3
4
5
6
def is_palindrome(s)
filtered_string = s.gsub(/[^a-zA-Z\d]/, "").downcase
reversed_string = filtered_string.reverse

filtered_string == reversed_string
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
function isPalindrome($s) {
$filteredString = strtolower(preg_replace('/[^a-zA-Z\d]/', '', $s));

$reversedString = strrev($filteredString);

return $filteredString === $reversedString;
}

$s = "A man, a plan, a canal: Panama";
echo isPalindrome($s)

PHP 方法筆記


LeetCode 傳送門 - Valid Palindrome