Skip to content

Instantly share code, notes, and snippets.

@MahraibFatima
Created February 5, 2025 12:47
Show Gist options
  • Save MahraibFatima/a27e516438bebbfe961bd7197175ed0e to your computer and use it in GitHub Desktop.
Save MahraibFatima/a27e516438bebbfe961bd7197175ed0e to your computer and use it in GitHub Desktop.
without extra multiple space between two words.
#include <iostream>
#include <string>
#include <stack>
#include <tuple>
using namespace std;
string reverseWords(string sentence) {
stack<string> words_stack;
string word = "";
for(int i=0; i<sentence.size(); ++i){
if(sentence[i] == ' ' && word != ""){
// cout<<word<<endl;
words_stack.push(word);
word = "";
}
if(sentence[i] != ' ')
word += sentence[i];
}
if(word != "") words_stack.push(word);
string new_sentence = "";
while(!words_stack.empty()){
new_sentence += ' ';
new_sentence += words_stack.top();
words_stack.pop();
}
new_sentence.erase(0,1);// remove first extra space
return new_sentence;
}
int main(){
string sentence = "queen loves king";
cout<< reverseWords(sentence);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment