38. Count and Say

男娘i 2022-07-15 01:16 240阅读 0赞

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.

Note: The sequence of integers will be represented as a string.

  1. public class Solution {
  2. public String countAndSay(int n) {
  3. String[] strs = new String[n];
  4. strs[0] = "1";
  5. StringBuilder sb = new StringBuilder();
  6. int sum = 0;
  7. char ch;
  8. for (int i = 1; i < n; i++) {
  9. ch = strs[i - 1].charAt(0);
  10. for (int j = 0; j < strs[i - 1].length(); j++) {
  11. if (strs[i - 1].charAt(j) != ch) {
  12. sb.append("" + sum + ch);
  13. ch = strs[i - 1].charAt(j);
  14. sum = 1;
  15. } else {
  16. sum++;
  17. }if(j==strs[i - 1].length()-1){
  18. sb.append("" + sum + ch);
  19. }
  20. }
  21. strs[i] = sb.toString();
  22. sb.delete(0, sb.length());
  23. sum=0;
  24. }
  25. return strs[n - 1];
  26. }
  27. }

发表评论

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

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

相关阅读