码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(38)题解: Count and Say

时间:2015-08-06 22:07:25      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/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.

 

思路:

题意有些模糊,看明白1211到111221就懂了。

 

AC代码:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         int tmp_n,count,k;
 5         string tmp,tmp_res,a[n];
 6         a[0]="1";
 7         for(int i=1;i<n;i++){
 8             tmp=a[i-1];
 9             tmp_res="";
10             tmp_n=tmp.size();
11             k=0;
12             count=1;
13             for(int j=1;j<tmp_n;j++){
14                 if(tmp[j]==tmp[j-1]){
15                     count++;
16                     continue;
17                 }
18                 else{
19                     tmp_res.push_back(0+count);
20                     tmp_res.push_back(tmp[j-1]);
21                     count=1;
22                 }
23             }
24             tmp_res.push_back(0+count);
25             tmp_res.push_back(tmp[tmp_n-1]);
26             a[i]=tmp_res;  
27         }
28     return a[n-1];
29     }
30 };

 

LeetCode(38)题解: Count and Say

标签:

原文地址:http://www.cnblogs.com/aezero/p/4709110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!