125. Valid Palindrome(E)

https://leetcode.com/problems/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.

Solution:

https://www.jiuzhang.com/problem/valid-palindrome/ 使用两根指针遍历整个字符串即可.

假定有指针i, j, 其中i是从前往后遍历, j是从后往前遍历.

当i在j左边时继续循环, 每一次将i右移到数字/字母上, j左移到数字/字母上,

比较二者对应的字符串内的字符是否相同, 不相同则原字符串不是回文串.

如果全部的比较都相同, 说明是回文串.

Last updated

Was this helpful?