LeetCode 125. Valid Palindrome

題目

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.

翻譯

給一個字串,不考慮大小寫與非字母數字的情況下,判斷這個字串是不是迴文。

範例:
"A man, a plan, a canal: Panama" --> true
"race a car" --> false (raceacar != racaecar)

注意:
你有考慮過空字串的情況嗎,在這邊我們定義空字串是一個迴文。

思路

這題我覺得頗簡單,不知道為啥通過率這麼低。

  1. 首先把字串轉為全小寫
  2. 將字串裡面不是字母與數字的部分去除
  3. 反轉字串判斷與上一個步驟處理過的字串相等

解題

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    //轉小寫
    s = s.toLowerCase();
    //取代非文字部分
    s = s.replace(/[^a-z0-9]/ig,"");
    //反轉
    var rev = s.split("").reverse().join("");
    //判斷反轉後是否與之前處理過的字串相等
    return s.indexOf(rev) == 0;
};

results matching ""

    No results matching ""