题目

leetcode 38 : 报数

 

算法思想 :这道题目是求出每个连续相同数字的个数+这个数字,因为第n次输出需要用到第n-1次的数据,所以我们自然而然想到递归去处理这一题,从n=1开始向下一级返回结果就可以了。

 

string countAndSay(int n) {
    string result = "";
      if(n == 1)
          result = "1";
      else
      {
          string tmp = "";
          tmp = countAndSay(n-1);
          int count = 0,i = 0,j = 0;
          while(i < tmp.length())
          {
              while(tmp[j] == tmp[i] && j < tmp.length())
              {
                j++;
                  count++;
              }
              result += to_string(count) + tmp[i];
            i = j;
            count = 0;    
        }
     }
     return result;
}

相关文章:

  • 2022-12-23
  • 2021-09-16
  • 2021-07-27
  • 2021-10-13
  • 2021-10-20
  • 2021-12-22
  • 2022-12-23
猜你喜欢
  • 2021-09-11
  • 2021-04-05
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
相关资源
相似解决方案