forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Prob: 186 Reverse words in a sentence
- Loading branch information
Showing
2 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/* | ||
* Given a string, you need to reverse the order of characters in each word within a sentence | ||
* while still preserving whitespace and initial word order. | ||
* | ||
* Example: | ||
* Input: She loves chocolate | ||
* Output: ehs sevol etalocohc | ||
* | ||
* Approach: | ||
* Use two indices to figure out non-whitespace characters, and reverse | ||
* the portion. | ||
*/ | ||
|
||
#include <iostream> | ||
#include <string> | ||
|
||
|
||
std::string reverse_words(std::string& sentence) | ||
{ | ||
for(int i = 0; i < sentence.length(); ++i) { | ||
if (sentence[i] != ' ') { | ||
int j = i; | ||
// let j find the end of non-whitespace portion | ||
while (j < sentence.length() && | ||
sentence[j] != ' ') { | ||
j++; | ||
} | ||
std::reverse(sentence.begin() + i, sentence.begin() + j); | ||
// reset i to next word. | ||
i = j - 1; | ||
} | ||
} | ||
return sentence; | ||
} | ||
|
||
int main() | ||
{ | ||
std::string sentence{"She loves chocolate"}; | ||
std::cout << "Input: " << sentence << std::endl; | ||
std::cout << "Output: " << reverse_words(sentence) << std::endl; | ||
return 0; | ||
} |