forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request soapyigu#118 from soapyigu/String
[String] Add solution to Valid Palindrome
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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.letters.contains(char) || CharacterSet.decimalDigits.contains(char) | ||
} | ||
} |