Swift Solution


  • 0
    R

    Here is my solution in Swift. It is basically the same as others posted here in Java and other languages. However, this solution is not approved due to it taking too much time with an input of 30. Has anyone gotten a solution working in swift?

        var s = "1"
    
        for _ in 1 ..< n {
    
            var newS = ""
            var count = 1
    
            for j in 1 ... s.count {
    
                if j == s.count || s[j-1] != s[j] {
                    newS += "\(count)\(s[j-1])"
                    count = 1
                } else { count += 1 }
    
            }
    
            s = newS
        }
    
        return s
    

  • 0
    B

    Hi raesu,

    I used the same code as yours but replacing a few lines for character comparison worked.

    let index1 = s.index(s.startIndex, offsetBy: j-1)
    let index2 = s.index(s.startIndex, offsetBy: j)
    if j == s.count || s[index1] != s[index2] {
       newS += "\(count)\(s[index1])"
        count = 1
    } else { count += 1 }
    

    From the Swift4 documentation related to characters deprecations , I followed the suggested way of accessing characters. This probably (seems) like an optimised access as compared to s[j] or s[j-1] .

    Do let me know your thoughts , Thanks.


Log in to reply
 

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