C# iterative solution


  • 0
    H
    static Dictionary<int, string> map = new Dictionary<int, string>();
        
        public string CountAndSay(int n) {
            if (map.ContainsKey(n)) return map[n];
            
            map[1] = "1";
            for(int i = 2; i <= n; i++) {
                if (map.ContainsKey(i)) continue;
                string val = map[i - 1];
                int j = 0;
                StringBuilder sb = new StringBuilder();
                while(j < val.Length) {
                    int k = j;
                    char c = val[j++];
                    while(j < val.Length && val[j] == c) j++;
                    sb.AppendFormat("{0}{1}", j - k, c);
                }
                
                map[i] = sb.ToString();
            }
            
            return map[n];
        }
    

Log in to reply
 

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