Last active
September 23, 2019 17:31
-
-
Save jakehawken/fff13586465ec147122507378b160f55 to your computer and use it in GitHub Desktop.
Leetcode #38: "The count-and-say sequence is the sequence of integers with the first five terms as following: 1) '1' 2) '11' 3) '21' 4. '1211' 5. '111221' 1 is read off as 'one 1' or 11. 11 is read off as 'two 1s' or 21. 21 is read off as 'one 2, then one 1' or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the ... sequence."
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func countAndSay(_ n: Int) -> String { | |
guard n > 0 else { | |
fatalError("Positive integers only!") | |
} | |
var last = "1" | |
if n == 1 { | |
return last | |
} | |
for _ in 2...n { | |
last = describeCharsIn(string: last) | |
} | |
return last | |
} | |
private func describeCharsIn(string: String) -> String { | |
guard !string.isEmpty else { | |
return "" | |
} | |
guard string.count > 1, let first = string.first else { | |
return "1\(string)" | |
} | |
var outputString = "" | |
var previous = first | |
var countOfPrevious = 1 | |
let finalIndex = string.count - 1 | |
var currentIndex = 0 | |
for current in string { | |
if currentIndex == 0 { | |
currentIndex += 1 | |
continue | |
} | |
let isFinalIndex = (currentIndex == finalIndex) | |
let isSameAsPrevious = (current == previous) | |
if isSameAsPrevious { | |
countOfPrevious += 1 | |
} | |
if isFinalIndex && isSameAsPrevious { | |
outputString += "\(countOfPrevious)\(current)" | |
} | |
else if isFinalIndex && !isSameAsPrevious { | |
outputString += "\(countOfPrevious)\(previous)" | |
outputString += "1\(current)" | |
} | |
else if !isFinalIndex && !isSameAsPrevious { | |
outputString += "\(countOfPrevious)\(previous)" | |
countOfPrevious = 1 | |
} | |
previous = current | |
currentIndex += 1 | |
} | |
return outputString | |
} | |
} | |
/* Current state of this solution on Leetcode (a 97% reduction in runtime!): | |
------------------------------------------------------------------------------------- | |
Runtime: 12 ms, faster than 64.89% of Swift online submissions for Count and Say. | |
Memory Usage: 20.9 MB, less than 100.00% of Swift online submissions for Count and Say. | |
------------------------------------------------------------------------------------- | |
Previously: | |
------------------------------------------------------------------------------------- | |
Runtime: 336 ms, faster than 5.33% of Swift online submissions for Count and Say. | |
Memory Usage: 21 MB, less than 100.00% of Swift online submissions for Count and Say. | |
------------------------------------------------------------------------------------- | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment