Leetcode题解-38. Count and Say

来源:互联网 发布:2014年流行的网络歌曲 编辑:程序博客网 时间:2024/06/03 09:07

Leetcode题解-38. Count and Say

题目

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: “1”
Example 2:

Input: 4
Output: “1211”

题目解释

n=1时,输出字符串“1”;
n=2时,数上次字符串(n=1的字符串)中的数值个数,因为上次字符串有1个1,所以输出“11”(表示1个一);
n=3时,由于上次字符是“11”,有2个1,所以输出“21”(表示2个1);
n=4时,由于上次字符串是21,有1个2和1个1,所以输出“1211”(表示1个2,2个1);
不难看出,这是一个简单的递归题目,也可以化递归为循环

代码

递归写法

class Solution {public:    string countAndSay(int n) {        string res = "1";        if(n != 1) {            n--;            while(n--) res = count(res);        }        return res;    }    string count(string s){        int count;        string res = "";        for(int i = 0; i < s.size(); i++){            count = 1;                      while((i+1 < s.size()) && s[i] == s[i+1]) {                count++;                i++;            }            res += to_string(count) + s[i];                              }        return res;    }};

循环写法

class Solution {public:    string countAndSay(int n) {        string res = "1";        while (--n) {            string cur = "";            for (int i = 0; i < res.size(); i++) {                int count = 1;                 while ((i + 1 < res.size()) && (res[i] == res[i + 1])){                    count++;                        i++;                }                cur += to_string(count) + res[i];            }            res = cur;        }        return res;    }};
原创粉丝点击