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.
如果一個短語是回文,將所有大寫字母轉為小寫字母、刪除所有非字母字符後,該回文向前或向後讀取皆相同。 字母字符包含文字和數值。 給予一個字串 s,如果是回文就回傳 true,否則回傳 false。 ex. Palindrome = level、refer
Example 1:
Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " " Output: true Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
Solution:
1. Input s 轉換成小寫字母。
2. Input s 將特殊符號移除。
3. 宣告 reverseWord 為反轉後的 s。
4. 回傳 s 中符合 reverseWord,完全符合為 0,沒有符合為 -1。
Code:
var isPalindrome = function(s) { s = s.toLowerCase() s = s.replace(/[^a-z0-9]/ig,"") let reverseWord = s.split("").reverse().join("") return s.indexOf(reverseWord) === 0 };
FlowChart:
Example 1
Input: s = "A man, a plan, a canal: Panama" s.toLowerCase() = a man, a plan, a canal: panama s.replace = amanaplanacanalpanama reverseWord = s.split("").reverse().join("") => amanaplanacanalpanama return true
Example 2
Input: s = "race a car" s.toLowerCase() = race a car s.replace = raceacar reverseWord = s.split("").reverse().join("") => racaecar return false
Example 3
Input: s = " " s.toLowerCase() = '' s.replace = '' reverseWord = s.split("").reverse().join("") => '' return true
.toLowerCase()
.toLowerCase():函式會回傳字符串轉換成英文小寫字母。 const sentence = 'The quick brown fox jumps over the lazy dog.' console.log(sentence.toLowerCase()); // expected output: "the quick brown fox jumps over the lazy dog."
.replace()
.replace(a, b):符合(a)內的字串後進行替換成(b),並回傳一個新的字串。 let text = "Mr Blue has a blue house and a blue car"; let result = text.replace(/blue/gi, "red"); console.log(result) // expected output: "Mr red has a red house and a red car"
.reverse()
.reverse():反轉一個陣列,陣列中的第一個元素變成最後一個,而最後一個元素變成第一個。 const array1 = ['one', 'two', 'three']; const reversed = array1.reverse(); console.log('reversed:', reversed); // expected output: "reversed:" Array ["three", "two", "one"]