And authentication algorithm leetcode 125. distal palindromic sequence

# Front end of the algorithm verification leetcode 125. palindromic sequence

Title Description

Given a string, verify that it is a palindrome string, consider only the alphabetic and numeric characters, can ignore letter case.

Description: In this problem, we define the empty string as a valid palindromic sequence.

Example 1:

输入: "A man, a plan, a canal: Panama"
输出: true

Example 2:

输入: "race a car"
输出: false

125. Verify palindromic sequence

Overview

Note that the title only consider the alphabetic and numeric characters and ignore the case of letters mentioned

prompt

Double pointer

Resolve

Solution a: api Man

You can solve the problem by calling crazy api, but more slowly

Solution two: the double pointer

Title said alphanumeric considered, ignoring case can first original string is then replaced by a regular all lowercase
further provided a head and tail pointers two aligned, inconsistencies once returns false

algorithm

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function (s) {
  // s = s.match(/\w/g);
  // if (s === null || s.length <= 1) {return true;}
  // return s.join('').toLowerCase() === s.reverse().join('')
  //   .toLowerCase();
  // 双指针法
  s = s.replace(/[^0-9a-zA-Z]/g, '').toLowerCase();
  let [i, j] = [0, s.length - 1];
  while (i <= j) {
    if (s.charAt(i++) !== s.charAt(j--)) {return false;}
  }
  return true;
};

Incoming operating results of test cases

input:"A man, a plan, a canal: Panama"
output:true

Results of the

执行用时 :64 ms, 在所有 javascript 提交中击败了99.91%的用户
内存消耗 :37.3 MB, 在所有 javascript 提交中击败了72.83%的用户

GitHub repository

125. Verify palindromic sequence

see more

More explanations

Guess you like

Origin www.cnblogs.com/moshuying/p/11903472.html