xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JavaScript palindrome string All In One

JavaScript palindrome string All In One

palindrome string / 回文 字符串


"use strict";

/**
 * 
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-05-25
 * @modified 
 * 
 * @description palindrome 回文 recursive
 * @augments 
 * @example 
 * @link 
 * 
 */

const log = console.log;

const palindromeChecker = (str = ``) => {
  const len = str.length;
  if(len <= 1) {
    return true;
  } else {
    return str === Array.from(str).reverse().join(``);
  }
};

// test
const t1 = palindromeChecker(`123`);
const t2 = palindromeChecker(`11`)
const t3 = palindromeChecker(`12`)
const t4 = palindromeChecker(`12345`)
const t5 = palindromeChecker(`12321`)

log(`t1`, t1)
log(`t2`, t2)
log(`t3`, t3)
log(`t4`, t4)
log(`t5`, t5)
// t1 false
// t2 true
// t3 false
// t4 false
// t5 true


// export default palindromeChecker;

// export {
//   palindromeChecker,
// };


performance optimization


const isPalindrome = (str = ``) => {
  const len = Math.floor(str.length / 2);
  str = str.toLocaleLowerCase();
  for (let i = 0; i < len; i++) {
    if (str[i] !== str[len - i - 1]) {
     // 提前结束
      return false;
    }
  }
  return true;
}

demos

const isPalindrome = (str) => {
  let rs = ``;
  let len = str.length;
  // 逆序字符串
  while(len--){
    rs += str[len];
  }
  return str === rs;
}

https://leetcode.com/problems/longest-palindrome/?envType=daily-question&envId=2024-06-04

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://www.cnblogs.com/xgqfrms/p/13371314.html

https://stackoverflow.com/questions/14813369/palindrome-check-in-javascript

https://www.freecodecamp.org/news/two-ways-to-check-for-palindromes-in-javascript-64fea8191fd7/

https://medium.com/free-code-camp/two-ways-to-check-for-palindromes-in-javascript-64fea8191fd7



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-05-25 19:28  xgqfrms  阅读(409)  评论(8编辑  收藏  举报