leetcode 38. Count and Say

来源:互联网 发布:苹果官网和淘宝旗舰店 编辑:程序博客网 时间:2024/06/06 15:02

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时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;
n=3时,由于上次字符是11,有2个1,所以输出21;
n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。
依次类推,写个countAndSay(n)函数返回字符串。

代码如下:

/* * 这道题很简单,但是很难理解 * 做法就是不断的遍历求解 * */public class Solution {    public String countAndSay(int n)    {        String res=1+"";        if(n==1)            return res;        else            for(int i=1;i<n;i++)                res=say(res);        return res;    }    public String say(String res)    {        String newRes="";        int i=0;        while(i<res.length())        {            int count=0;            int j=i;            while(j<res.length() && res.charAt(i)==res.charAt(j))            {                count++;                j++;            }            newRes=newRes+count+res.charAt(i);            i=j;        }        return newRes;    }}

下面是C++的做法,这道题说实话很难搞懂是什么意思

代码如下:

#include <iostream>#include <string>using namespace std;class Solution {public:    string countAndSay(int n)     {        string res = "1";        if (n == 1)            return res;        else        {            for (int i = 1; i < n; i++)                res = say(res);            return res;        }    }    string say(string s)    {        string res = "";        int i = 0;        while (i < s.length())        {            int count = 0;            int j = i;            while (j < s.length() && s[i]==s[j])            {                count++;                j++;            }            res = res + to_string(count) + s[i];            i = j;        }        return res;    }};