038 Count and Say[E]

1 題目描述

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

1. 12. 113. 214. 12115. 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.

難度:Easy

2 題目樣例

Example 1:Input: 1Output: "1"Example 2:Input: 4Output: "1211"

3 題意分析

將數字從1開始,將當前數字轉化為口語對應的數字。比如1口語是1個1,記作11;11讀作2個1,記作21;21讀作1個2,1個1,記作1211……

4 思路分析

一個一個數過去即可。

代碼實現如下

class Solution { public: string countAndSay(int n) { if (n == 0) return ""; 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; }};

5 後記

這個題目我不是很喜歡...因為沒什麼技術含量。

推薦閱讀:

LeetCode 簡略題解 - 301~400
leetcode也開始收費了,大家怎麼看?
Leetcode-38-Count-and-Say(學渣的痛大神們不懂。。。)
【LeetCode】#1——TwoSum
[leetcode algorithms]題目7

TAG:演算法 | LeetCode | 演算法設計 |