My 0ms c++ solution


  • -2
    Y
    class Solution {
    public:
        string countAndSay(int n) {
            if(n <= 0) return string();
            string say = "1";
            for(int i = 1; i < n; i++) {
                say = convert(say);
            }
            return say;
        }
        string convert(const string &say) {
            stringstream ret;
            char temp = say[0];
            int count = 0;
            for(int i = 0; i <= say.length(); i++) {
                if(say[i] == temp) count++;
                else {
                    ret << count << temp;
                    count = 1;
                    temp = say[i];
                }
            }
            return ret.str();
        }
    };

  • 0
    G

    At line #15, you have "for(int i = 0; i <= say.length(); i++)". Won't say[i] take a value out of array when i = say.length()?


  • 0
    Y

    Thanks!! I will correct it!


Log in to reply
 

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