Skip to content

Commit

Permalink
Merge pull request soapyigu#118 from soapyigu/String
Browse files Browse the repository at this point in the history
[String] Add solution to Valid Palindrome
  • Loading branch information
soapyigu authored Nov 11, 2016
2 parents 9c3c977 + 5ae7689 commit da38a8e
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions String/ValidPalindrome.swift
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)
}
}

0 comments on commit da38a8e

Please sign in to comment.