Count and Say

来源:互联网 发布:bs软件开发 编辑:程序博客网 时间:2024/05/22 02:08

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.

class Solution {public:    string countAndSay(int n) {        string result = "1";    n--;    while (n > 0)    {    string temp = result;    result.erase(0, result.length());    char curValue = temp[0];    int count = 1;    for (int i = 1; i < temp.length(); i++)    {    if (temp[i] == curValue)    {    count++;    }    else    {    result.append(1, (char)(count+'0'));    result.append(1, curValue);    count = 1;    curValue = temp[i];    }    }    result.append(1, (char)(count+'0'));    result.append(1, curValue);    n--;    }    return result;     }};


0 0
原创粉丝点击