LeetCode38 Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.(Easy)

分析:

按照题目要求以此生成新串即可,注意第一个是串是1,即下标从1开始。

同时,复习使用to_string.

代码:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string s = "1";
 5         for (int i = 1; i < n; ++i) {
 6             int count = 1;
 7             string temp;
 8             for (int j = 0; j < s.size(); ++j) {
 9                 if (j == s.size() - 1 || s[j] != s[j + 1]) {
10                     temp += to_string(count);
11                     temp += s[j];
12                     count = 1;
13                 }
14                 else {
15                     count ++;
16                 }
17             }
18             s = temp;
19         }
20         return s;
21     }
22 };

 

 
posted @ 2016-08-24 21:28  wangxiaobao1114  阅读(118)  评论(0编辑  收藏  举报