c# solution, using dictionary


  • 0
    B

    public class Solution {
    private static Dictionary<int, string> storelist=new Dictionary<int, string>();//create a dictionary to store key is nth term and extarct from dic instead going loop again;
    public string CountAndSay(int n) {
    if(storelist.ContainsKey(n)){//if key already exist, return directly
    return storelist[n];
    }
    else{
    if(n==1){
    storelist[1]="1";//store the value for 1 as initial step
    }
    else{
    storelist[n]=readstring(CountAndSay(n-1));
    }
    return storelist[n];
    }
    }
    //handle the string return from n-1th term
    private string readstring(string input){
    string output="";
    char cur=input[0];
    int count=0;//count the number of current char
    int length=input.Length;
    foreach(char a in input){//loop every char in string
    if(a==cur){

                count +=1;
            }
            else{
                output=output+ count+cur;
                cur=a;
                count=1;
                
            }
        }
        output=output+ count+cur;//reach terminate char in string, store the last char not append to output string
        return output;
    }
    

    }


Log in to reply
 

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