Leetcode 38: Count and Say

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 38: Count and Say相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode题意分析&解答38. Count and Say

Leetcode38. Count and Say

LeetCode 38: Count and Say

[LeetCode 38] Count and Say

leetcode-38 Count And Say

LeetCode 38. Count and Say