forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountAndSay.swift
33 lines (27 loc) · 875 Bytes
/
CountAndSay.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Question Link: https://leetcode.com/problems/count-and-say/
* Primary idea: Recursion to get previous string, then iterate and generate current one.
*
* Time Complexity: O(n^2), Space Complexity: O(1)
*
*/
class CountAndSay {
func countAndSay(_ n: Int) -> String {
if n == 1 {
return "1"
}
let previousStr = countAndSay(n - 1)
var currentChar = previousStr.first!, currentCount = 0, res = ""
for (i, char) in previousStr.enumerated() {
if char == currentChar {
currentCount += 1
} else {
res += "\(currentCount)\(currentChar)"
currentCount = 1
currentChar = char
}
}
res += "\(currentCount)\(currentChar)"
return res
}
}