[C#] Correct output, but memory limit exceeded. Why?


  • 0
    S
    public class Solution {
        public string CountAndSay(int n) {
            string curr = n.ToString();
            string newNum = "";
            for (int i = 0; i < n; i++) {
                char c = curr[0];
                int numChars = 0;
                for (int j = 0; j < curr.Length; j++) {
                    if (curr[j] == c) {
                        numChars++;
                    } else {
                        newNum += numChars.ToString() + c;
                        c = curr[j];
                        numChars = 1;
                    }
                }
                newNum += numChars.ToString() + c;
                curr = newNum;
                newNum = "";
            }
            return curr;
        }
    }

  • 0
    H

    Here is the solution without string builder

    public class Solution {
    public string CountAndSay(int n) {
    string result = "1";
    string num = "1";
    string current = string.Empty;

            for (int i = 1; i < n; i++)
            {
                char firstChar = num[0];
                int count = 0;
                current = string.Empty;
                for (int j = 0; j < num.Length; j++)
                {
                    if (firstChar == num[j])
                        count++;
                    else
                    {
                        current = current + count.ToString() + firstChar;
                        firstChar = num[j];
                        count = 1;
                    }
                }
                current = current + count.ToString() + firstChar;
    
                result = result + "," + current;
                num = current;
            }
            if(current== string.Empty)
            return "1";
            return current;
    }
    

    }


Log in to reply
 

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