LeetCode38——Count and Say

来源:互联网 发布:智能家庭解决方案知乎 编辑:程序博客网 时间:2024/06/06 02:32

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.

难度系数:

容易

实现

string countAndSay(int n) {    if (n == 1) {        return string("1");    }    string prev = countAndSay(n-1);    int before = 0;    int count = 0;    string curr;    for (int i = 0; i < prev.length(); ++i) {        if (prev[i]-'0' == before) {            count++;            continue;        } else if (before != 0) {            curr.append(1, '0' + count);            curr.append(1, '0' + before);        }        before = prev[i]-'0';        count = 1;    }    if (before != 0 && count != 0) {        curr.append(1, '0' + count);        curr.append(1, '0' + before);    }    return curr;}
0 0
原创粉丝点击