forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ValidPalindrome.swift
43 lines (36 loc) · 1.08 KB
/
ValidPalindrome.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
39
40
41
42
43
/**
* Question Link: https://leetcode.com/problems/valid-palindrome/
* Primary idea: Two Pointers, compare left and right until they meet
*
* Note: ask interviewer if digit matters
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class ValidPalindrome {
func isPalindrome(_ s: String) -> Bool {
let chars = Array(s.lowercased().characters)
var left = 0
var right = chars.count - 1
while left < right {
while left < right && !isAlpha(chars[left]) {
left += 1
}
while left < right && !isAlpha(chars[right]) {
right -= 1
}
if chars[left] != chars[right] {
return false
} else {
left += 1
right -= 1
}
}
return true
}
private func isAlpha(_ char: Character) -> Bool {
guard let char = String(char).unicodeScalars.first else {
fatalError("Character is invalid")
}
return CharacterSet.alphanumerics.contains(char)
}
}