LeetCode-38. Count and Say

来源:互联网 发布:公司申请软件著作权 编辑:程序博客网 时间:2024/06/05 21:01

问题:https://leetcode.com/problems/count-and-say/?tab=Description
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.
计数然后表达出来。n=1,输出1;n=2,之前有1个1,所以输出11;n=3,之前有两个1,输出21;n=4,之前是一个2,一个1,输出1211……给出n,输出第n个序列。结果也要用字符串的形式表示。
分析:如果n=1,返回”1”。如果n>1,需要用到迭代函数。遍历,如果前一个数和当前数相等,计数器加1.如果不等,得出当前的结果。
C++代码:

class Solution {public:    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;    }};

代码来自:http://blog.csdn.net/booirror/article/details/43736753

0 0
原创粉丝点击