Swift sliding window solution

  • 0

    My Swift solution with sliding window was time limit exceeded. Is it because Swift is slower?

    class Solution {
        func lengthOfLongestSubstring(_ s: String) -> Int {
            var i = 0
            var maxNum = 0
            var checkDict = [String: Int]()
            for j in 0..<s.count {
                let character = s[s.index(s.startIndex, offsetBy: j)]
                if let existingIndex = checkDict[String(character)] {
                    i = max(existingIndex, i)
                maxNum = max(maxNum, j - i + 1)
                checkDict[String(character)] = j + 1
            return maxNum

  • 0

    I converted the string to array first and it worked! Because Swift string index is not O(1), it's O(length of string).

    let sArr = Array(s)

  • 1

    Yes, the same solution in many languages works fine, but fails because of swift implementation details. The window for swift solution should be shifted up

Log in to reply

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