forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidPalindrome.swift
39 lines (33 loc) · 912 Bytes
/
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
/**
* Question Link: https://leetcode.com/problems/valid-palindrome/
* Primary idea: For every index in the first half of the String, compare two values at mirroring indices.
*
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class ValidPalindrome {
func isPalindrome(_ s: String) -> Bool {
var i = 0, j = s.count - 1
let sChars = Array(s.lowercased())
while i < j {
while !sChars[i].isAlphanumeric && i < j {
i += 1
}
while !sChars[j].isAlphanumeric && i < j {
j -= 1
}
if sChars[i] != sChars[j] {
return false
} else {
i += 1
j -= 1
}
}
return true
}
}
extension Character {
var isValid: Bool {
return isLetter || isNumber
}
}