-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path557.reverse-words-in-a-string-iii.cpp
More file actions
61 lines (60 loc) · 1.35 KB
/
557.reverse-words-in-a-string-iii.cpp
File metadata and controls
61 lines (60 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* @lc app=leetcode id=557 lang=cpp
*
* [557] Reverse Words in a String III
*
* https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
*
* algorithms
* Easy (79.60%)
* Likes: 3198
* Dislikes: 189
* Total Accepted: 507.9K
* Total Submissions: 635.8K
* Testcase Example: `"Let's take LeetCode contest"`
*
* Given a string s, reverse the order of characters in each word within a
* sentence while still preserving whitespace and initial word order.
*
*
* Example 1:
* Input: s = "Let's take LeetCode contest"
* Output: "s'teL ekat edoCteeL tsetnoc"
* Example 2:
* Input: s = "God Ding"
* Output: "doG gniD"
*
*
* Constraints:
*
*
* 1 <= s.length <= 5 * 10^4
* s contains printable ASCII characters.
* s does not contain any leading or trailing spaces.
* There is at least one word in s.
* All the words in s are separated by a single space.
*
*
*/
// @lc code=start
class Solution
{
public:
string reverseWords(string s)
{
int m = 0, n = 0;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == ' ' || i == s.size() - 1)
{
n = i == s.size() - 1 ? i : i - 1;
while (m < n)
swap(s[m++], s[n--]);
m = i + 1;
n = i + 1;
}
}
return s;
}
};
// @lc code=end