aboutsummaryrefslogtreecommitdiff
path: root/count_and_say.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-04-17 21:05:50 -0600
committerJack Sangdahl <[email protected]>2025-04-17 21:05:50 -0600
commitbc581d176d97f5fd8d47679407d77d87b2dfdc70 (patch)
tree4420705cc3c29eea386e947f024339e0dbc749b7 /count_and_say.py
parentea06e128606ea42e2b2c25d73e94e7d352f5e79d (diff)
downloadleetcode-bc581d176d97f5fd8d47679407d77d87b2dfdc70.tar.gz
leetcode-bc581d176d97f5fd8d47679407d77d87b2dfdc70.zip
38. count and say
Diffstat (limited to 'count_and_say.py')
-rw-r--r--count_and_say.py35
1 files changed, 35 insertions, 0 deletions
diff --git a/count_and_say.py b/count_and_say.py
new file mode 100644
index 0000000..e8521b3
--- /dev/null
+++ b/count_and_say.py
@@ -0,0 +1,35 @@
+# 38. Count and Say
+from re import findall
+
+"""
+the count-and-say sequence is a sequence of digit strings defined by the
+recursive formula:
+- countAndSay(1) = "1"
+- countAndSay(n) is the way you would "say" the digit string from
+'countAndSay(n - 1)', which is then converted into a different digit string
+to determine how you "say" a digit string, split it into minimal number of
+substrings such that each substring contains exactly one unique digit. then
+for each substring, say the number of digits, then say the digit, finally,
+concatenate every said digit. given a positive integer 'n', return the n'th
+term of the count and say sequence.
+"""
+
+
+class Solution(object):
+ def countAndSay(self, n):
+ """
+ :type n: int
+ :rtype: str
+ """
+ ans = "1"
+ for _ in range(n - 1):
+ ans = "".join(
+ str(len(group)) + digit for group, digit in findall(r"((.)\2*)", ans)
+ )
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.countAndSay(n=4))
+ print(obj.countAndSay(n=1))