Skip to content

Commit ea28a88

Browse files
authored
Merge pull request soapyigu#217 from p-sun/master
Solve isPalindrome by comparing mirroring indices
2 parents f9a0077 + 183f3f8 commit ea28a88

File tree

1 file changed

+15
-30
lines changed

1 file changed

+15
-30
lines changed

String/ValidPalindrome.swift

Lines changed: 15 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,28 @@
11
/**
22
* 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+
*
65
* Time Complexity: O(n), Space Complexity: O(n)
76
*
87
*/
98

109
class ValidPalindrome {
1110
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] {
2623
return false
27-
} else {
28-
left += 1
29-
right -= 1
3024
}
3125
}
32-
3326
return true
3427
}
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

Comments
 (0)