Skip to content

Commit 0e8c0ab

Browse files
committed
Prob: 186 Reverse words in a sentence
1 parent 1f5c065 commit 0e8c0ab

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
| Current Status| Stats |
88
| :------------: | :----------: |
9-
| Total Problems | 185 |
9+
| Total Problems | 186 |
1010

1111
</center>
1212

@@ -269,3 +269,7 @@ pattern = "abba", str = "dog dog dog dog" should return false.| [word_pattern.cp
269269
price of a stock on ith day. If you are permitted to only complete
270270
one transaction per day (i.e buy one and sell one stock), design
271271
an algorithm to find the maximum profit.| [best_time_to_buy_sell.cpp](leet_code_problems/best_time_to_buy_sell.cpp)|
272+
| Given a sentence, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.|
273+
Example:
274+
Input: She loves chocolate
275+
Output: ehs sevol etalocohc|[reverse_words.cpp](leet_code_problems/reverse_words.cpp)|

leet_code_problems/reverse_words.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* Given a string, you need to reverse the order of characters in each word within a sentence
3+
* while still preserving whitespace and initial word order.
4+
*
5+
* Example:
6+
* Input: She loves chocolate
7+
* Output: ehs sevol etalocohc
8+
*
9+
* Approach:
10+
* Use two indices to figure out non-whitespace characters, and reverse
11+
* the portion.
12+
*/
13+
14+
#include <iostream>
15+
#include <string>
16+
17+
18+
std::string reverse_words(std::string& sentence)
19+
{
20+
for(int i = 0; i < sentence.length(); ++i) {
21+
if (sentence[i] != ' ') {
22+
int j = i;
23+
// let j find the end of non-whitespace portion
24+
while (j < sentence.length() &&
25+
sentence[j] != ' ') {
26+
j++;
27+
}
28+
std::reverse(sentence.begin() + i, sentence.begin() + j);
29+
// reset i to next word.
30+
i = j - 1;
31+
}
32+
}
33+
return sentence;
34+
}
35+
36+
int main()
37+
{
38+
std::string sentence{"She loves chocolate"};
39+
std::cout << "Input: " << sentence << std::endl;
40+
std::cout << "Output: " << reverse_words(sentence) << std::endl;
41+
return 0;
42+
}

0 commit comments

Comments
 (0)