C# solution with explanations in the code


  • 0
    H

    public class Solution {

    public string CountAndSay(int n) {
    
        string s ="1";
    
        // Doing this n-1 times to get the nth sequence
        for( int i = 1; i < n; i++){
         // Need a new working StringBuilder each time
         StringBuilder sb = new StringBuilder();
            int count = 1;
            for(int j = 1; j <= s.Length; j++){
                // If the last character of the previous sequence or when next char is not the current char 
                if( j == s.Length || s[j] != s[j-1]){
                    sb.Append(count);
                    sb.Append(s[j-1]);
                    count = 1;
                }
                else{
                    count++;
                }
            }
            s = sb.ToString();
        }
        return s;
    }
    

    }


Log in to reply
 

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