Count and say[easy on LeetCode]

来源:互联网 发布:软件更新 编辑:程序博客网 时间:2024/06/10 11:45

原题地址:https://leetcode.com/problems/count-and-say/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 1:

Input: 1
Output: “1”

Example 2:

Input: 4
Output: “1211”

解题思路

首先列出n=1到n=7的结果:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221

由题目和输出可以看出,n的结果与n-1的结果有关。
因为n=1属于特殊情况,需要单独赋值。
又因为n=1的输出为1,即个位数,属于特殊情况,所以n=2的结果也需要单独赋值为11。
当n>2时,将n-1得出的字符串代入赋值于一个变量res,并初始化一个空字符串newres。
因为题目中提到需要记录相同字符的数量,所以我们初始化一个变量count=1。
从res的第二位(i)开始,向左一位比较,如果相同,count+1;如果不同,count重置为1。比较完,i+1,重复相同操作。
当 i 移动到res最后一位时(特殊处理),将count和res[ i ]写入newres。

代码实现 in C++:

class Solution {public:    string countAndSay(int n) {        if (n == 1)            return "1";        if (n == 2)            return "11";        string res = countAndSay(n - 1);        string newres = "";        int count = 1;        for (int i = 1; i < res.size(); ++i) {            if (res[i] != res[i-1]) {                newres.push_back('0'+count);                newres.push_back(res[i-1]);                count = 1;            } else {                count++;            }            if (i == res.size() - 1) {                newres.push_back('0'+count);                newres.push_back(res[i]);            }        }        return newres;    }};
原创粉丝点击