Swift Solution - 29ms (90%)


  • 0
    Z
    class Solution {
        func countAndSay(_ n: Int) -> String {
            
            if n == 1 {
                return "1"
            }
            
            var currentTerm: String = "1"
            var newTerm = ""
            var count = 0
            var char: Character = currentTerm.characters.first!
            
            for i in 2...n {
                newTerm = ""
                count = 0
                char = currentTerm.characters.first!
                
                for currentChar in currentTerm.characters {
                    if currentChar == char {
                        count += 1
                    } else {
                        newTerm += "\(count)\(char)"
                        char = currentChar
                        count = 1
                    }
                }
                
                newTerm += "\(count)\(char)"
                currentTerm = newTerm
            }
            
            return currentTerm
        }
    }
    

    Fairly fast & straightforward.


Log in to reply
 

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