【LeetCode】C# 38、Count and Say

来源:互联网 发布:大数据的特点包含 编辑:程序博客网 时间:2024/06/17 04:12

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”

思路:利用StringBuilder.Append() 将prev字符串读写出来。完成一个循环后curr 给prev,进入下一个循环。

public class Solution {    public string CountAndSay(int n) {        StringBuilder curr=new StringBuilder("1");        StringBuilder prev;        int count;        char say;        for (int i=1;i<n;i++){            prev=curr;            curr=new StringBuilder();                   count=1;            say=prev[0];            for (int j=1;j<prev.Length;j++){                if (prev[j]!=say){                    curr.Append(count).Append(say);                    count=1;                    say=prev[j];                }                else count++;            }            curr.Append(count).Append(say);        }                           return curr.ToString();    }}
原创粉丝点击