import Foundation
/*
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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, generate the nth sequence.
*/
/*
Thinking:
遍历数字,得到Count, Number(用栈结构,每次取出上一个数字,相同则计数,不同则Append )
计算完后展平,得到新的数字,
然后重复
*/
func countAndSay(_ n: Int ) -> String {
//计算出 (count, Number)
guard n > 0 else {
return "0"
}
let nStr = String(1)
var stackArray: [(Int, Character)] = [(Int, Character)]()
func pushStack(_ c: Character) {
if let last = stackArray.last {
if (last.1 == c) {
let count = last.0 + 1
stackArray[stackArray.count - 1] = (count, last.1)
} else {
stackArray.append((1, c))
}
} else {
stackArray.append((1, c))
}
}
func emptyStack() {
stackArray.removeAll()
}
func stackToString() -> String {
var strArray: [String] = [String]()
for value in stackArray {
strArray.append(String(value.0))
strArray.append(String(value.1))
}
emptyStack()
return strArray.joined()
}
func calc(_ nStr: String) -> String {
for c in nStr.characters {
pushStack(c)
}
return stackToString()
}
var newString = nStr
for _ in (0 ..< n-1) {
newString = calc(newString)
}
return newString
}
//print(countAndSay(0))
//print(countAndSay(1))
print(countAndSay(3))
38. Count and Say
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 原题 报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:1, 11, 21, 1211, 11...
- 1.描述 The count-and-say sequence is the sequence of intege...
- 问题 The count-and-say sequence is the sequence of integers...