Skip to content

Commit

Permalink
Prob: 186 Reverse words in a sentence
Browse files Browse the repository at this point in the history
  • Loading branch information
mandliya committed Feb 3, 2018
1 parent 1f5c065 commit 0e8c0ab
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

| Current Status| Stats |
| :------------: | :----------: |
| Total Problems | 185 |
| Total Problems | 186 |

</center>

Expand Down Expand Up @@ -269,3 +269,7 @@ pattern = "abba", str = "dog dog dog dog" should return false.| [word_pattern.cp
price of a stock on ith day. If you are permitted to only complete
one transaction per day (i.e buy one and sell one stock), design
an algorithm to find the maximum profit.| [best_time_to_buy_sell.cpp](leet_code_problems/best_time_to_buy_sell.cpp)|
| Given a sentence, 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|[reverse_words.cpp](leet_code_problems/reverse_words.cpp)|
42 changes: 42 additions & 0 deletions leet_code_problems/reverse_words.cpp
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;
}

0 comments on commit 0e8c0ab

Please sign in to comment.