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

Leetcode 38: Count and Say

时间:2017-11-07 12:11:24      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:new   dsa   log   integer   res   enc   size   col   put   

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"


Notes: should ask clarify question what is after 4, I was confused by the example input where I thought we only need to count dup 1s.

 1 public class Solution {
 2     public string CountAndSay(int n) {
 3         var result = "1";
 4         
 5         while (n-- > 1)
 6         {
 7             var sb = new StringBuilder();
 8             
 9             int i = 0;
10             while (i < result.Length)
11             {
12                 int j = i + 1;
13                 while (j < result.Length && result[i] == result[j])
14                 {                
15                     j++;
16                 }
17                 
18                 sb.Append(j - i);
19                 sb.Append(result[i]);
20                 i = j;
21             }
22             
23             result = sb.ToString();
24         }
25         
26         return result;
27     }
28 }

 

Leetcode 38: Count and Say

标签:new   dsa   log   integer   res   enc   size   col   put   

原文地址:http://www.cnblogs.com/liangmou/p/7798253.html

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