forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidPalindromeII.swift
32 lines (30 loc) · 1 KB
/
ValidPalindromeII.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 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
*
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class ValidPalindromeII {
func validPalindrome(_ s: String) -> Bool {
let array = Array(s)
return isPalindrome(array, 0, array.count - 1)
}
fileprivate func isPalindrome(_ array: [Character], _ i: Int, _ j: Int, alreadyRemoved: Bool = false) -> Bool {
var i = i, j = j
while i < j {
if array[i] != array[j] {
if alreadyRemoved {
return false
} else {
return isPalindrome(array, i + 1, j, alreadyRemoved: true) ||
isPalindrome(array, i, j - 1, alreadyRemoved: true)
}
} else {
i += 1
j -= 1
}
}
return true
}
}