Swift solution (working around String limitations)


  • 0
    J
    class Solution {
        func lengthOfLongestSubstring(_ s: String) -> Int {
            let n = s.characters.count
            var set = Set<Character>()
            var ans = 0, i = 0, j = 0
            
            // Working with an array of characters since you cannot subscript String
            // and using String.index(string.startIndex, offsetBy: x) is just a no go 
            // for performance on very large inputs
    
            var charArr = [Character]()
            for char in s.characters {
                charArr.append(char)
            }
            
            while i<n && j<n {
                if !set.contains(charArr[j]) {
                    set.insert(charArr[j])
                    j += 1
                    ans = max(ans, j-i)
                } else {
                    set.remove(charArr[i])
                    i += 1
                }
            }
            return ans
        }
    }
    

Log in to reply
 

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