Swift solution time exceeded


  • 0
    S

    Hey,

    I managed to write a solution to this in Swift, but it says that the time is exceeded. I´m most certain that it has to do with Swift rather than my code, as it seems pretty much the fastest solution. Does Swift need a longer timout for this question?

    class Solution {
        func isPalindrome(_ s: String) -> Bool {
            guard !s.isEmpty else { return true }
            let strippedString = stripUnwantedChars(s)
            
            var i = 0
            let chars = strippedString.characters
            var j = chars.count - 1
            while (i < j) {
                if charsAreEqual(chars, i, j) {
                    i = i+1
                    j = j-1
                } else {
                    return false
                }
            }
            return true
        }
        
        func charsAreEqual(_ chars: String.CharacterView, _ i: Int, _ j: Int) -> Bool {
            let startIndex = chars.startIndex
            let frontChar = chars[chars.index(startIndex, offsetBy: i)]
            let backChar = chars[chars.index(startIndex, offsetBy: j)]
            return frontChar == backChar
        }
        
        func stripUnwantedChars(_ s: String) -> String {
            let alphanumericsSet = CharacterSet.alphanumerics.inverted
            return s.components(separatedBy: alphanumericsSet).joined().lowercased()
        }
    }
    

    Edit: Just as I finished the post, I tried the easiest way to do it in Swift, and that works! So I guess my way of accessing characters in a String via Index is quite slow. Can somebody explain?

    class Solution {
        func isPalindrome(_ s: String) -> Bool {
            guard !s.isEmpty else { return true }
            let strippedString = stripUnwantedChars(s)
            
            let reversed = String(strippedString.characters.reversed())
            return reversed == strippedString 
            
        }
        
        func stripUnwantedChars(_ s: String) -> String {
            let alphanumericsSet = CharacterSet.alphanumerics.inverted
            return s.components(separatedBy: alphanumericsSet).joined().lowercased()
        }
    }
    

Log in to reply
 

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