[LeetCode] 125. Valid Palindrome

有效的回文。题意很简单,验证给的input是否是一个有效的回文。例子,

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

思路也很简单,two pointer逼近。注意去掉所有non-characters和non-digits,也就是去掉所有的标点符号。这里只比较input里面的字母是不是回文。

时间O(n)

空间O(1)

 1 /**
 2  * @param {string} s
 3  * @return {boolean}
 4  */
 5 var isPalindrome = function (s) {
 6     if (s === null || s.length === 0) return true;
 7     const alphanum = s.toLowerCase().replace(/[\W]/g, "");
 8     let left = 0;
 9     let right = alphanum.length - 1;
10     while (left < right) {
11         if (alphanum[left] !== alphanum[right]) {
12             return false;
13         }
14         left++;
15         right--;
16     }
17     return true;
18 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12194820.html