38. 外观数列

  1. class Solution {
  2. public String countAndSay(int n) {
  3. if (n == 1)
  4. return "1";
  5. String ans = "1";
  6. for (int i = 2; i <= n; i++) {
  7. ans = next(ans);
  8. }
  9. return ans;
  10. }
  11. private String next(String str) {
  12. // 对字符串str进行描述
  13. char[] chs = str.toCharArray();
  14. StringBuilder descripe = new StringBuilder();
  15. int index = 0;
  16. int count;
  17. char cur;
  18. while (index < chs.length) {
  19. count = 0;
  20. cur = chs[index];
  21. while (index < chs.length && chs[index] == cur) {
  22. ++count;
  23. ++index;
  24. }
  25. descripe.append(count);
  26. descripe.append(cur);
  27. }
  28. return descripe.toString();
  29. }
  30. }