[LeetCode] 125. 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.

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.

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

验证回文串。

如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。

字母和数字都属于字母数字字符。

给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意很简单,验证给的 input 是否是一个有效的回文。思路也很简单,two pointer 逼近。注意

  • 只比较 input 里面的字母,如果是数字或者空格就跳过
  • 不需要区分大小写 - 把字母都变成小写再比较

时间O(n)

空间O(1)

JavaScript实现

 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 };

 

Java实现

 1 class Solution {
 2     public boolean isPalindrome(String s) {
 3         // corner case
 4         if (s == null || s.length() == 0) {
 5             return true;
 6         }
 7 
 8         // normal case
 9         int left = 0;
10         int right = s.length() - 1;
11         while (left < right) {
12             while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
13                 left++;
14             }
15             while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
16                 right--;
17             }
18             if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
19                 return false;
20             }
21             left++;
22             right--;
23         }
24         return true;
25     }
26 }

 

相关题目

125. Valid Palindrome

234. Palindrome Linked List

680. Valid Palindrome II

LeetCode 题目总结

posted @ 2020-01-15 03:37  CNoodle  阅读(418)  评论(0编辑  收藏  举报