Last executed input: " ".


  • 0
    T

    My answer to the first problem of reversing words in a string.

    #include <iostream>
    #include <sstream>
    #include <string>
    #include <vector>
    using namespace std;
    
    
    class Solution {
    public:
        void reverseWords(string &s) {
            stringstream ss(s);
            vector<string> store;
            string item;
            while(getline(ss, item, ' ')){
                store.push_back(item);
            }
            s.clear();
            for (int i = store.size()-1; i >= 0; i--){
                s += store[i] + ' ';
            } 
            s.erase(s.end()-1);
        }
    };
    

    It works on my computer. But I got a runtime error here. Can't fix the problem. Thanks to anyone who can help me out.


  • 1
    G

    you need to deal with empty string case. Also, what you need is actually a stack

    class Solution {
    public:
        void reverseWords(string &s) {
            stringstream ss(s);
            stack<string> store;
            string item;
            while(getline(ss, item, ' ')){
                    if (item.size())
                            store.push(item);
            }
            s.clear();
            while (!store.empty()) {
                    s += (store.top() + ' ');
                    store.pop();
            }
            if (s.size())
                    s.pop_back();
        }
    };
    

  • 0
    T

    Many thanks, ghostincircuit!
    Besides, what is the benefit of using stack instead of vector here? I've searched the differences between those two, but I don't see the advantages of stack. Could you please shed some light on it ?


  • 0
    G

    I thought you are using the vector as a stack, first in last out(to implement reverse order). A vector can of course work very well, it's just a matter of taste.


Log in to reply
 

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