38. Count and Say

ゝ一纸荒年。 2022-03-07 11:38 323阅读 0赞

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
  6. 1 is read off as "one 1" or 11.
  7. 11 is read off as "two 1s" or 21.
  8. 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.

  1. Example 1:
  2. Input: 1
  3. Output: "1"
  4. Example 2:
  5. Input: 4
  6. Output: "1211"

难度:easy

题目:
count-and-say 序列如下如示:

  1. 1. 1
  2. 2. 11
  3. 3. 21
  4. 4. 1211
  5. 5. 111221
  6. 1 读作1111
  7. 11 读作2121
  8. 21 读作12,接着11 1211

给定一个整数n 大于等于1小于等于30, 产生第n组序列。
注意:每项由整数组成的序列以字符串表示。

Runtime: 3 ms, faster than 72.13% of Java online submissions for Count and Say.
Memory Usage: 25.8 MB, less than 98.33% of Java online submissions for Count and Say.

  1. class Solution {
  2. public String countAndSay(int n) {
  3. String str = "";
  4. for (int i = 0; i < n; i++) {
  5. str = generateNext(str);
  6. }
  7. return str;
  8. }
  9. private String generateNext(String s) {
  10. if (s.isEmpty()) {
  11. return "1";
  12. }
  13. // add and end flag
  14. s += ".";
  15. int counter = 1;
  16. StringBuilder str = new StringBuilder();
  17. for (int i = 1; i < s.length(); i++) {
  18. if (s.charAt(i) != s.charAt(i - 1)) {
  19. str.append(counter).append(s.charAt(i - 1));
  20. counter = 1;
  21. } else {
  22. counter++;
  23. }
  24. }
  25. return str.toString();
  26. }
  27. }

发表评论

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

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

相关阅读