Leetcode NO.38 Count and Say

来源:互联网 发布:java老师王克晶年薪 编辑:程序博客网 时间:2024/06/06 08:45

本题题目要求如下:

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.

本题没有什么算法可言,就是对连续出现的同样数字记数。。比如1121,就出现了2个1,1个2,1个1,所以结果是211211,代码如下:

class Solution {public:    string countAndSay(int n) {        string ret = "1";        for (int i = 1; i < n; ++i) {            ret = generate(ret);        }        return ret;    }private:     string generate(string str) {        string ret = "";        char tmp = str[0];        int cnt = 1;        for (int i = 1; i < str.length(); ++i) {            if (str[i] == tmp) {                ++cnt;            }            else {                ret = ret + to_string(cnt) + tmp;                cnt = 1;                tmp = str[i];            }        }        ret = ret + to_string(cnt) + tmp;        return ret;    }};





0 0
原创粉丝点击