Skip to content

Commit

Permalink
Refactor solution to the Valid Palindrome II
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Nov 4, 2023
1 parent e9253b8 commit 26c5865
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions String/ValidPalindromeII.swift
Original file line number Diff line number Diff line change
@@ -1,38 +1,40 @@
/**
* Question Link: https://leetcode.com/problems/valid-palindrome-ii/
* Primary idea: Take advantage of validPalindrome, and jump left and right separately to get correct character should be deleted
* Primary idea: Two pointers. Move left and right when they are equal or cannot separate by moving either side, otherwise move one direction and update the flag.
*
* Time Complexity: O(n), Space Complexity: O(n)
* Time Complexity: O(n), Space Complexity: O(1)
*
*/

class ValidPalindromeII {
func validPalindrome(_ s: String) -> Bool {
var i = 0, j = s.count - 1, isDeleted = false
let s = Array(s)
return isValid(true, s) || isValid(false, s)
}

private func isValid(_ skipLeft: Bool, _ s: [Character]) -> Bool {
var i = 0, j = s.count - 1, alreadySkipped = false


while i < j {
if s[i] == s[j] {
i += 1
j -= 1
} else {
if alreadySkipped {
if s[i] != s[j] {
if isDeleted {
return false
} else {
alreadySkipped = true
if skipLeft {
i += 1
} else {
if s[i + 1] == s [j] && s[j - 1] == s[i] {
i += 1
j -= 1
} else if s[i + 1] == s[j] {
i += 1
isDeleted = true
} else if s[j - 1] == s[i] {
j -= 1
isDeleted = true
} else {
return false
}
}
} else {
i += 1
j -= 1
}
}

return true
}
}

0 comments on commit 26c5865

Please sign in to comment.