[LeetCode] 38. Count and Say
1. 1
2. 11
3. 21
4. 1211
5. 111221Input: 1
Output: "1"Input: 4
Output: "1211"Last updated
1. 1
2. 11
3. 21
4. 1211
5. 111221Input: 1
Output: "1"Input: 4
Output: "1211"Last updated
class Solution {
func countAndSay(_ n: Int) -> String {
var res: String = "1";
if(n < 2) {
return res;
}
for i in 2...n {
res = self.handler(output: res);
}
return res;
}
func handler(output: String) -> String {
let chars = Array(output);
var text = "";
var count = 0;
var current:Character = "a";
for i in 0..<chars.count {
let char = chars[i];
if(char == current) {
count += 1;
}
else {
if(count != 0) {
text = "\(text)\(count)\(current)";
}
current = char;
count = 1;
}
}
if(count != 0) {
text = "\(text)\(count)\(current)";
}
return text;
}
}