0ms C++ simple solution


  • 0
    L
     string helper(string s){
        char c = s[0];
        int count = 1;
        stringstream ss;
        for(int i = 1; i < s.size(); i ++){
            if(s[i] != c){
                ss << count << c;
                c = s[i];
                count = 1;
            }else{
                count ++;
            }
        }
        
        ss << count << c;
        return ss.str();
    }
    
    string countAndSay(int n) {
        string str = "1";
        for(int i = 1; i < n; i ++ ){
            str = helper(str);
        }
        return str;
    }

  • 0
    Y

    @lanshan317 i have a question!
    string countAndSay(int n, string output = "1") {
    if(n == 1) return output;
    string input = "1";
    if(output != "1") input = output;
    string newoutput = "";
    char last = input[0];
    int count = 0;
    for(int i = 0; i < input.length(); i++){
    if(input[i] == last) count++;
    else{
    newoutput += to_string(count);
    newoutput += last;
    last = input[i];
    count = 1;
    }
    }
    if(count != 0){
    newoutput += to_string(count);
    newoutput += last;
    }
    return countAndSay(n-1, newoutput);
    }
    this is my code. i think your solution is very similar to my code. but running time of my code
    is 6ms .... do you know why?


Log in to reply
 

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