Swift AC solution


  • 0
    A
    class Solution {
        func say(_ digits: [Int]) -> [Int] {
            var result = [Int]()
            var idx = 0
            while idx < digits.count {
                let currentDigit = digits[idx]
                var cnt = 1
                var idx2 = idx + 1
                while idx2 < digits.count && digits[idx2] == currentDigit {
                    cnt += 1
                    idx2 += 1
                }
                result.append(cnt)
                result.append(currentDigit)
                idx = idx2
            }
            return result
        }
        
        func countAndSay(_ n: Int) -> String {
            var s = [1]
            var k = 1
            while k < n {
                s = say(s)
                k += 1
            }
            return s.reduce("", { str, i in str + String(i) })
        }
    }
    

Log in to reply
 

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