forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidPalindromeII.swift
38 lines (34 loc) · 1.02 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
33
34
35
36
37
38
/**
* 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 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 {
return false
} else {
alreadySkipped = true
if skipLeft {
i += 1
} else {
j -= 1
}
}
}
}
return true
}
}