Count and Say

描述

The count-and-say sequence is the sequence of integers beginning as follows:

  1. 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. // Count and Say
  2. // @author 连城 (http://weibo.com/lianchengzju)
  3. // 时间复杂度O(n^2),空间复杂度O(n)
  4. class Solution {
  5. public String countAndSay(int n) {
  6. String s = "1";
  7. while (--n > 0)
  8. s = getNext(s);
  9. return s;
  10. }
  11. String getNext(final String s) {
  12. StringBuilder sb = new StringBuilder();
  13. for (int i = 0; i < s.length();) {
  14. int j = notEqual(s, i);
  15. sb.append(j - i);
  16. sb.append(s.charAt(i));
  17. i = j;
  18. }
  19. return sb.toString();
  20. }
  21. // find the first char that not equal to fromIndex
  22. private static int notEqual(final String s, int fromIndex) {
  23. final char target = s.charAt(fromIndex);
  24. int i = fromIndex;
  25. for (; i < s.length(); ++i) {
  26. if (s.charAt(i) != target) break;
  27. }
  28. return i;
  29. }
  30. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/string/count-and-say.html