LeetCode: count and say

来源:互联网 发布:windows登录密码忘记 编辑:程序博客网 时间:2024/06/06 09:56

题目:The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

解题过程: 题目比较难懂,大意就是n=1时,输出字符串“1”,n=2时,数上次字符串中的数值个数,因为上次字符串有一个1,所以输出“11”, n = 3 时,n= 2中有2个1,所以是“21”,以此类推。读懂题目就好做了,只要用递归的方法就能够解决了。

代码:

string countAndSay(int n){    if (n <= 0) return string();    string say = "1";    for(int i =2; i<=n; i++){         say = countAndSayAssist(say);    }    return say;}string countAndSayAssist(const string &str){    stringstream ss;    int count = 0;    char c = str[0]    for(int i =0; i<str.length(); i++){        if(str[i] == c) count+++;        else {             ss<<count<<str[i];             count=1;             c = str[i];        }    }    return ss.str();}