Skip to content

LeetCode题解:125. 验证回文串,翻转数组,JavaScript,详细注释 #314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chencl1986 opened this issue Mar 9, 2021 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:125. 验证回文串

解题思路:

  1. 回文串的含义是:一个字符串,翻转后仍然等于其本身。
  2. 将输入字符串中,字母和数字取出(其中大写字母需要转成小写),存入一个数组。
  3. 利用数组的reverse方法,即可将字符串翻转,因此将翻转前后的字符串进行对比即可。
/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function (s) {
  let arr = []; // 使用数组存储合格的字符

  // 遍历s,将合格的字符存入arr
  for (const char of s) {
    // 字母和数字字符都是合格的
    if (char >= '0' && char <= '9') {
      arr.push(char);
    } else if (char >= 'a' && char <= 'z') {
      arr.push(char);
    }
    // 大小写需要忽略,此处将大写转换为小写
    else if (char >= 'A' && char <= 'Z') {
      arr.push(char.toLowerCase());
    }
  }

  // 将数组和翻转后的数组,转换成字符串对比即可
  return arr.join('') === arr.reverse().join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant