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

680. 验证回文字符串 Ⅱ #58

Open
buuing opened this issue Nov 12, 2021 · 0 comments
Open

680. 验证回文字符串 Ⅱ #58

buuing opened this issue Nov 12, 2021 · 0 comments

Comments

@buuing
Copy link
Owner

buuing commented Nov 12, 2021

给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。

示例 1:

输入: s = "aba"
输出: true

示例 2:

输入: s = "abca"
输出: true
解释: 你可以删除c字符。

示例 3:

输入: s = "abc"
输出: false

提示:

  • 1 <= s.length <= 105
  • s 由小写英文字母组成

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。




  • 双指针 + 贪心
const validPalindrome = (s, lev = 0) => {
  let left = 0, right = s.length - 1
  while (left < right) {
    if (s[left] !== s[right]) {
      if (lev >= 1) return false
      const leftStr = s.slice(left, right)
      const rightStr = s.slice(left + 1, right + 1)
      return validPalindrome(leftStr, lev + 1) || validPalindrome(rightStr, lev + 1)
    }
    left++
    right--
  }
  return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant