1
1
/**
2
2
* Question Link: https://leetcode.com/problems/valid-palindrome/
3
- * Primary idea: Two Pointers, compare left and right until they meet
4
- *
5
- * Note: ask interviewer if digit matters
3
+ * Primary idea: For every index in the first half of the String, compare two values at mirroring indices.
4
+ *
6
5
* Time Complexity: O(n), Space Complexity: O(n)
7
6
*
8
7
*/
9
8
10
9
class ValidPalindrome {
11
10
func isPalindrome( _ s: String ) -> Bool {
12
- let chars = Array ( s. lowercased ( ) . characters)
13
-
14
- var left = 0
15
- var right = chars. count - 1
16
-
17
- while left < right {
18
- while left < right && !isAlpha( chars [ left] ) {
19
- left += 1
20
- }
21
- while left < right && !isAlpha( chars [ right] ) {
22
- right -= 1
23
- }
24
-
25
- if chars [ left] != chars [ right] {
11
+ // Make String into an array of lowercase Characters
12
+ let characters = s. lowercased ( ) . characters
13
+
14
+ // Only keep alphanumeric characters.
15
+ let cleaned = characters. filter { character in
16
+ return character. description. rangeOfCharacter ( from: CharacterSet . alphanumerics) != nil
17
+ }
18
+
19
+ // Compare values at mirroring indices.
20
+ let total = cleaned. count
21
+ for i in 0 ..< total/ 2 {
22
+ if cleaned [ i] != cleaned [ total - 1 - i] {
26
23
return false
27
- } else {
28
- left += 1
29
- right -= 1
30
24
}
31
25
}
32
-
33
26
return true
34
27
}
35
-
36
- private func isAlpha( _ char: Character ) -> Bool {
37
- guard let char = String ( char) . unicodeScalars. first else {
38
- fatalError ( " Character is invalid " )
39
- }
40
-
41
- return CharacterSet . alphanumerics. contains ( char)
42
- }
43
- }
28
+ }
0 commit comments