My solution in C#


  • 0
    P
            /// <summary>
            /// Method to count the number in the previous sequence and then say the number. 
            /// It will keep on doing this until it reaches the limit. 
            /// </summary>
            /// <param name="limit">limit of range</param>
            /// <returns>nth String of count n say</returns>
            string CountAndSay(int limit)
            {
                string s = string.Empty;
                List<string> lstAll = new List<string>();
    
                // check for boundary tests.
                if (limit == 0) 
                    return string.Empty;
                else if (limit == 1) 
                    return "1";
    
                // set the default counter to 1 to match the limit. 
                int counter = 1;
                // insert the default first string in the list
                lstAll.Add("1");
    
                string lastStr = string.Empty;
                int charCount = 0;
    
                while (counter < limit)
                {
                    // get the last string we got from Count & Say
                    lastStr = lstAll[counter - 1];
                    // get it's first chat to match remaining
                    char val = lastStr[0];
                    // set the charater count as 1.
                    charCount=1;
    
                    for (int i = 1; i < lastStr.Length; i++)
                    {
                        if (lastStr[i] == val)
                        {
                            charCount++;
                        }
                        else
                        {
                            // add the count and number in the string 
                            s = s + charCount.ToString() + val.ToString();
                            // take new character to match remaining.
                            val = lastStr[i];
                            // set character counter as 1.
                            charCount = 1;
                        }
                    }
    
                    // add the count and number in the string, that we got in the end 
                    s = s + charCount.ToString() + val.ToString();
                    lstAll.Add(s);
                    // initialize the s string to compute next in the limit.
                    s = string.Empty;
                    counter++;
                }
    
                // if the question ask for all the strings upto the limit, return lstAll List
                // else if the question ask for only nth string, return one string.
                return lstAll[counter-1];
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.