Created
February 5, 2025 12:47
-
-
Save MahraibFatima/a27e516438bebbfe961bd7197175ed0e to your computer and use it in GitHub Desktop.
without extra multiple space between two words.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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