【Leetcode】38. Count and Say

布满荆棘的人生 2022-03-09 03:06 271阅读 0赞
  1. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1. 1
  2. 2. 11
  3. 3. 21
  4. 4. 1211
  5. 5. 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

  1. Input: 1
  2. Output: "1"

Example 2:

  1. Input: 4
  2. Output: "1211"

题目大意:

第一个字符串只有’1’,我们在输入2时第一个字符串里只有1个’1’,输出’11’。第二个字符串中相邻且相同的’1’有两个,输入n=3则输出’21’。第三个字符串中有1个’2’、1个’1’,输入n=4则输出’1211’。

  1. class Solution:
  2. def countAndSay(self, n: int) -> str:
  3. ans = ['1']
  4. j = 1
  5. while j < n:
  6. new_ans = []
  7. i = 0
  8. while i < len(ans):
  9. time = 1
  10. while i + 1 < len(ans) and ans[i+1] == ans[i]:
  11. time += 1
  12. i += 1
  13. time = str(time)
  14. new_ans.append(time)
  15. new_ans.append(ans[i])
  16. i += 1
  17. ans = new_ans
  18. j += 1
  19. tmp = ''.join(ans)
  20. return tmp

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读