C# solution


  • 0
    R
    public class Solution {
        public string CountAndSay(int n) {
            int i=2; int j=0; string prev =""; string curr =""; int count = 0;
            if(n==1) return "1";
            if(n==2) return "11";
            prev = "11";
            while(i < n)
            {
                curr=""; j=1; count = 1;
                while(j < prev.Length)
                {
                    if(prev[j] != prev[j-1]) // Count not the same as previous element, so append to current string.
                     {
                        curr = curr + count + prev[j-1];
                        count = 1; // reset count for next.
                     }
                    else
                     {
                        count++; // count same as previous, so increment.
                     }
                                    
                    j++;
                }
                
                curr = curr + count + prev[j-1]; 
                prev = curr; // Assign current to previous for next iteration.
                i++;
            }
          return curr;  
        }
    }
    

Log in to reply
 

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