Skip to content
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

LeetCode题解:125. 验证回文串,双指针,JavaScript,详细注释 #316

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

Comments

@chencl1986
Copy link
Owner

解题思路:125. 验证回文串

解题思路:

  1. 回文串的含义是:一个字符串,翻转后仍然等于其本身。
  2. 如果用两个指针,从两端向中间推进,它们对应的字符如果始终相等,那么就是回文串。
  3. 如果指针移动时,遇到非法字符,则需要跳过。
/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
  // 使用两个指针,分别从首尾向中间推进
  let i = 0;
  let j = s.length - 1;

  // 不断对比每个合法字符,直到两个指针相遇
  while (i < j) {
    // 如果两个指针遇到非法字符,则跳过
    // 为避免指针移动出现i >= j的情况,增加判断
    while (!check(s[i]) && i < j) {
      i++;
    }
    while (!check(s[j]) && i < j) {
      j--;
    }

    // 如果发现两个字符不相等,则s不是回文串,返回false即可
    // 无论判断结果如何,都将指针向中间移动一位
    if (s[i++].toLowerCase() !== s[j--].toLowerCase()) {
      return false;
    }
  }

  // 能够退出循环,表示没有发现不相等的字符,s是回文串
  return true;
};

// 判断字符是否合法
const check = (char) => {
  if (
    (char >= '0' && char <= '9') ||
    (char >= 'a' && char <= 'z') ||
    (char >= 'A' && char <= 'Z')
  ) {
    return true;
  }

  return false;
};
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