LeetCode (Simple) Number Reporting (c#)

Posted by brucec on Fri, 04 Oct 2019 15:59:27 +0200

The title of the report sequence is a sequence of integers, in which the order of the integers is reported to get the next number. The first five items are as follows:

  1. 1
    
  2. 11
    
  3. 21
    
  4. 1211
    
  5. 111221
    

1 is read as "one 1" ("one one one"), or 11.
11 is read as "two 1s" ("two one"), or 21.
21 is read as "one 2", "one 1" ("one two", "one one one"), or 1211.

Given a positive integer n (1 < n < 30), the n-th term of the output sequence is obtained.

Note: The order of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

First of all, we should understand the meaning of the topic.

  1. 1=>11 means a 1.
  2. 11=>21 means two 1
  3. 21=>1211 means two or two 1.
    Sort the code I gave in turn as follows
public static string CountAndSay(int n)
        {
            string res = "1";
            if (n==1)
            {
                return res;
            }
            for (int i = 1; i < n; i++)
            {
                int Count = 0;//Calculate the total number of individual letters
                Stack st = new Stack();//Record the current letter
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < res.Length; j++)
                {
                    if (j==0)
                    {
                        st.Push(res[0]);
                        Count += 1;
                    }
                    else if ((char)st.Peek()==res[j])
                    {
                        Count += 1;
                    }
                    else
                    {
                            sb.Append(Count == 0 ? "1" : Count.ToString() + st.Pop());
                            st.Push(res[j]);
                            Count = 1;
                    }
                    if (j==res.Length-1)
                    {
                        sb.Append(Count == 0 ? "1" : Count.ToString() + st.Pop());
                    }
                }
                res = sb.ToString();
            }
            return res;
        }