Why ostream::operator<< is slower than string::push_back


  • 0
    N

    Here is the solution using << operator in stringstream and the run time is 4ms

    class Solution {
    public:
        string countAndSay(int n) {
            string res = "1";
            
            while(n-- > 1) {
                string tmp = res;
                stringstream ss;
                int cnt = 1;
                for(int i = 0; i < tmp.length(); i++) {
                    if(i + 1 < tmp.length() && tmp[i] == tmp[i + 1]) {
                        cnt++;
                    } else {
                        ss << cnt << tmp[i];
                        cnt = 1;
                        res = ss.str();
                    }
                }
            }
            return res;
        }
    };
    

    On the other hand, when using string::push_back, the run time is only 0ms

    class Solution {
    public:
        string countAndSay(int n) {
            string res = "1";
        
            while(n-- > 1) {
                string tmp = res;
                res.clear();
                int cnt = 1;
                for(int i = 0; i < tmp.length(); i++) {
                    if(i + 1 < tmp.length() && tmp[i] == tmp[i + 1]) {
                        cnt++;
                    } else {
                        res.push_back(cnt + '0');
                        res.push_back(tmp[i]);
                        cnt = 1;
                    }
                }
            }
            return res;
        }
    };
    

    Can someone help me understand why stringstream is so slow? Am I missing anything?

    Thanks in advance!


Log in to reply
 

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