C# solution: simply count


  • 0
    B

    Do not forget to append the last letters after the loop of the array.

    public class Solution 
    {
        public string CountAndSay(int n) 
        {
            if (n <= 0) return "";
    
            if (n == 1) return "1";
    
            var result = new StringBuilder("1");
    
            while(n > 1)
            {
                var tempResult = new StringBuilder();
    
                int count = 1;
                for (int i = 1; i < result.Length; i++)
                {
                    if (result[i - 1] == result[i])
                    {
                        count++;
                    }
                    else
                    {
                        tempResult.Append(count);
                        tempResult.Append(result[i-1]);
                        count = 1;
                    }
                }
                
                // This part is easy to forget
                tempResult.Append(count);
                tempResult.Append(result[result.Length - 1]);
    
                result = tempResult;
                
                n--;
            }
    
            return result.ToString();
        }
    }
    

Log in to reply
 

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