Swift solution - O(n) time


  • 0
    class Solution {
        func isPalindrome(_ s: String) -> Bool {
            if s.isEmpty {
                return true
            }
            
            let characters = Array(s.lowercased().unicodeScalars)
            let alphanumericsSet = CharacterSet.alphanumerics
            var left = 0
            var right = s.unicodeScalars.count - 1
            var leftCharacter = characters[left]
            var rightCharacter = characters[right]
    
            while left <= right {
                leftCharacter = characters[left]
                rightCharacter = characters[right]
                while left < right && !alphanumericsSet.contains(leftCharacter) {
                    left += 1
                    leftCharacter = characters[left]
                }
                while left < right && !alphanumericsSet.contains(rightCharacter) {
                    right -= 1
                    rightCharacter = characters[right]
                }
                if leftCharacter != rightCharacter {
                    return false
                }
                left += 1
                right -= 1
            }
            
            return true
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.