Reverse Words In String

Given an input string, reverse the string word by word.

For example, Given s = "the sky is blue", return "blue is sky the".

Solution: Double Reverse

  1. Reverse the individual words, we get the below string.
  2. Reverse the whole string from start to end and you get the desired output.

Note: If we need to trim the space at the start and end of the string, using stack is a better solution

Solution: Using stack

  1. Traverse the string and push each word
  2. Pop each word and append it to the new string.
void reverseWords(string &s) {
    stack<string> m;
    string word = "";
    for (auto ch: s) {
        if (ch != ' ') {
            word += ch;
        } else if (!word.empty()) {
            m.push(word);
            word = "";
        }
    }

    if (!word.empty()) m.push(word);

    s = "";
    while(!m.empty()) {
        s += m.top();
        m.pop();
        s += m.empty() ? "" : " ";
    }        
}

results matching ""

    No results matching ""