[LeetCode]38. Count and Say

来源:互联网 发布:东莞农村商业银行网络 编辑:程序博客网 时间:2024/05/29 07:39

Description

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

Example1:
Input: 1
Output: “1”

Example2:
Input: 4
Output: “1211”

Discussion

第一个数字为“1”,第二个数字是第一个数字的读法“一个1”或“11”,第三个数字是第二个数字的读法“两个1”或“21”,以此类推……

知道了规律后,我们就可以确定算法了。每一个字符串都是根据上一个字符串来生成的。这就转变成了一个计数问题。我们只需要遍历一遍,每次检查当前字符是否和上一个字符相同,相同的话就把计数器加一,不同的话就在新的字符串中添加相应的信息。

算法的时间复杂度为O(n^2)。

C++ Code

class Solution {public:    string countAndSay(int n) {        vector<string> answer;      //保存结果,answer[i-1]保存第i个结果        answer.push_back("1");        for(int i = 1; i < n; i++)        {            string tmp = answer[i - 1];        //记录上一次的字符串            string new_answer = "";     //新字符串的结果            int count = 1;            for(int j = 1; j <= tmp.length(); j++)            {                //遍历到tmp末尾后一个的时候,就把前面的数字加到answer中,并跳出                if(j == tmp.length())                {                    new_answer = new_answer + to_string(count) + tmp[j - 1];                    break;                }                //判断当前字符是否和前一个字符相同,如果相同则计数器加一,否则把前一段相同的字符加入到answer中。                if(tmp[j] == tmp[j - 1])                {                    count ++;                }                else                {                    new_answer = new_answer + to_string(count) + tmp[j - 1];                    count = 1;                }            }            answer.push_back(new_answer);        }        return answer[n - 1];    }};