forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor solution to the Valid Palindrome II
- Loading branch information
Showing
1 changed file
with
20 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |