Last active
February 3, 2020 14:35
-
-
Save spurscho/8d9421a193fbbd28dd6a8ed50e07ff96 to your computer and use it in GitHub Desktop.
38. Count and Say
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 { | |
if n == 1 { return "1" } | |
let val = countAndSay( n - 1 ) | |
let res = "\(count(String(val)))" | |
return res | |
} | |
func count(_ str: String) -> String { | |
guard str.count > 0 else { | |
return "count is zero" | |
} | |
var cnt = 0 | |
var oldValue: Character = str.first! | |
var resStr = "" | |
for item in str { | |
if item == oldValue { | |
cnt += 1 | |
} else { | |
resStr.append("\(cnt)\(oldValue)") | |
cnt = 1 | |
} | |
oldValue = item | |
} | |
resStr.append("\(cnt)\(oldValue)") | |
return resStr | |
} | |
} | |
let sol = Solution() | |
print(sol.countAndSay(5)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment