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

Day271:给定一个字符串 s,最多删除一个字符。判断是否能成为回文字符串。 #1092

Open
Genzhen opened this issue Mar 31, 2021 · 3 comments
Labels
算法 teach_tag

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Mar 31, 2021

/*
输入: "aba"
输出: True
输入: "abca"
输出: True
注意: 字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。
*/

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
欢迎大家在下方发表自己的优质见解

二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

@Genzhen Genzhen added the 算法 teach_tag label Mar 31, 2021
@savoygu
Copy link

savoygu commented Apr 2, 2021

function isCanbePalindrome(s) {
  let l = 0, r = s.length - 1
  while(l < r) {
    if (s[l] !== s[r]) { // 一旦遇到不同的,要么取左舍右,要么取右舍左
      return isPalindrome(l, r - 1) || isPalindrome(l + 1, r)
    }
    l++
    r--
  }
  
  return true

  function isPalindrome(l, r) {
    while(l < r) {
      if (s[l] !== s[r]) return false
      l++
      r--
    }
    return true
  }
}

@savoygu
Copy link

savoygu commented Apr 2, 2021

function isCanbePalindrome(s) {
  function isPalindromeR(l , r, valid) {
    while(l < r) {
      if (s[l] !== s[r]) {
        if (!valid) return false // 一旦 valid 为  false, 则说明是第二次不同
        return isPalindromeR(l, r - 1, false) || isPalindromeR(l + 1, r, false)
      }
      l++
      r--
    }
    return true
  }

  return isPalindromeR(0, s.length - 1, true)
}

@DaphnisLi
Copy link

const main = (s) => {
  let left = 0
  let right = s.length - 1
  let maxDelete = 1
  while (left <= right) {
    if (s[left] === s[right]) {
      left++
      right--
    } else {
      if (maxDelete) {
        if (s[left + 1] === s[right]) {
          left = left + 2
          right--
        } else if (s[left] === s[right - 1]) {
          left++
          right = right - 2
        }
        maxDelete--
      } else return false
    }
  }
  return true
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 teach_tag
Projects
None yet
Development

No branches or pull requests

3 participants