Count and Say-LeetCode

来源:互联网 发布:软件测试书籍 知乎 编辑:程序博客网 时间:2024/06/16 07:29

The count-and-say sequence is the sequence of integers beginning as follows:
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.

用到了一个平时没有用到的stringstream,用来将int转化为string,十分便捷,使用方法见下面的博文链接。

http://www.cppblog.com/Sandywin/archive/2007/07/13/27984.html

代码:

class Solution {public:    string getnextstr(string str)    {    stringstream ss;    char key =  str[0];     char current = str[0];    int count = 0;    for (int i = 0; i < str.length(); i++)    {    current = str[i];    if (key == current)    {    count++;         }    else    {    ss<<count<<key;    key = current;    count = 1;    }    }    ss<<count<<key;    return ss.str();    }    string countAndSay(int n) {    string result = "1";    if ( n <= 0)    {    return NULL;    }    if (n == 1)      {    return result;    }    for (int i = 0; i < n - 1; i++)    {    result = getnextstr(result);    }    return result;    }};


 

0 0
原创粉丝点击