当前位置:网站首页>14 -- validate palindrome string II

14 -- validate palindrome string II

2022-06-25 14:43:00 JH_ Cao

subject

Github link
Given a non empty string s, Delete at most one character . Determine whether it can be a palindrome string .

Example 1:

Input : s = “aba” Output : true
Example 2:

Input : s = “abca” Output : true explain : You can delete c character .

  • Ideas
  1. Double pointer , Move the pointer left and right , See if it's equal
  2. Be careful not to delete the left and right elements , Although the complexity of deleting the last element of the array is O(1), But the complexity of deleting the first element of an array is O(n)
  3. Skip left or right , Should be considered once

The code is as follows :

func validPalindrome(_ s: String) -> Bool {
        var temp = Array(s).map({String($0)})
        var isDeleted = false
        
        func helper1( _ left: Int, _ right: Int) -> Bool {
            var left = left
            var right = right
            
            while left < right {
                if temp[left] == temp[right] {
                    left += 1
                    right -= 1
                } else {
                    if isDeleted {
                        return false
                    }
                    isDeleted = true
                    return helper1(left + 1, right) || helper1(left, right - 1) //  Delete left or right , Take into account 
                }
            }
            
            return true
        }
        
        return helper1(0, temp.count - 1)
    }
原网站

版权声明
本文为[JH_ Cao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251437245479.html