C# Solution using recursion


  • 0
    H
    public class Solution {
        public string CountAndSay(int n) {
            return ReturnNext("1", 0, n-1);
        }
        
        public string ReturnNext(string s, int count, int n) {
            if(count == n) return s;
            StringBuilder sb = new StringBuilder();
            char cn = s[0]; //current number/character
            int ccc = 1; //current character count
            for(int i = 1; i < s.Length; i++) {
                if(s[i] == cn) {
                    ccc++;
                } else {
                    sb.Append("" + ccc + cn); //append answer
                    ccc = 1; //reset
                    cn = s[i];
                }
            }
            sb.Append("" + ccc + cn); //final buffer values need to be appended to answer
            return ReturnNext(sb.ToString(), count+1, n);
        }
    }
    

Log in to reply
 

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