125. Verify palindrome string | swipe question punch

create by db on 2021-3-11 20:10:12

Recently revised in 2021-3-11 20:17:16

Idle time to have a tight mind, busy time to have leisure fun

Verify palindrome string > directory

  • Topic describes
  • Thought analysis
  • AC code
  • conclusion

Topic describes

Returns the directory

Given a string, verify that it is a palindrome string, considering only alphanumeric characters, regardless of letter case.

Note: In this case, we define an empty string as a valid palindrome string.

Example 1:

Input: "A man, A plan, A canal: PanamaCopy the code

Example 2:

Input: "race a car" Output: falseCopy the code

Thought analysis

Speaking of palindromes, think of a palindrome poem. Su Dongpo’s Bodhisattva · Palindrome Summer Boudoir Resentment:

Liuting wind quiet people sleep day, day sleep people quiet wind willow court. Sweat thin shirt cool, cool shirt thin sweat fragrance. Hand red ice bowl lotus root, lotus root bowl ice red hand. Lang laugh lotus root silk long, long lotus root laugh Lang.Copy the code

Idea 1: Flip the contrast

The palindrome is the same thing. Just consider letters and numbers and not be case sensitive, so we take what’s valid in the string and flip it over.

Idea 2: Dual-pointer comparison

Before and after the two Pointers, take out the valid content of the string, one by one comparison.

AC code

Solution 1: Reverse contrast

/ * * *@param {string} s
 * @return {boolean}* /
var isPalindrome = function (s) {
  let s1 = s.replace(/[^0-9a-zA-Z]/g.' ').toLowerCase()
  let s2 = s1.split(' ').reverse().join(' ')
  return s1 === s2
}
Copy the code

Solution 2: Double pointer comparison

/ * * *@param {string} s
 * @return {boolean}* /
var isPalindrome = function (s) {
  // Double pointer comparison
  s = s.replace(/[^0-9a-zA-Z]/g.' ').toLowerCase()
  let left = 0
  let right = s.length - 1

  while (left < right) {
    if(s[left] ! = s[right]) {return false
    }
    left++
    right--
  }
  return true
}
Copy the code

conclusion

Returns the directory

A very simple problem, persimmon first pick soft pinch…

March hello, spring flowers. Come on!

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign

Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address

Document agreement



dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.

Based on thegithub.com/danygitgitOn the creation of works.

Use rights other than those authorized by this License agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.