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:
  6. string countAndSay(int n) {
  7. string s("1");
  8. while (--n)
  9. s = getNext(s);
  10. return s;
  11. }
  12. string getNext(const string &s) {
  13. stringstream ss;
  14. for (auto i = s.begin(); i != s.end(); ) {
  15. auto j = find_if(i, s.end(), bind1st(not_equal_to(), *i));
  16. ss << distance(i, j) << *i;
  17. i = j;
  18. }
  19. return ss.str();
  20. }
  21. };

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