1
+ // Source : https://leetcode.com/problems/reverse-words-in-a-string/
2
+ // Author : henrytien
3
+ // Date : 2022年02月09日
4
+
5
+ /* ****************************************************************************************************
6
+ *
7
+ * Given an input string s, reverse the order of the words.
8
+ *
9
+ * A word is defined as a sequence of non-space characters. The words in s will be separated by at
10
+ * least one space.
11
+ *
12
+ * Return a string of the words in reverse order concatenated by a single space.
13
+ *
14
+ * Note that s may contain leading or trailing spaces or multiple spaces between two words. The
15
+ * returned string should only have a single space separating the words. Do not include any extra
16
+ * spaces.
17
+ *
18
+ * Example 1:
19
+ *
20
+ * Input: s = "the sky is blue"
21
+ * Output: "blue is sky the"
22
+ *
23
+ * Example 2:
24
+ *
25
+ * Input: s = " hello world "
26
+ * Output: "world hello"
27
+ * Explanation: Your reversed string should not contain leading or trailing spaces.
28
+ *
29
+ * Example 3:
30
+ *
31
+ * Input: s = "a good example"
32
+ * Output: "example good a"
33
+ * Explanation: You need to reduce multiple spaces between two words to a single space in the reversed
34
+ * string.
35
+ *
36
+ * Constraints:
37
+ *
38
+ * 1 <= s.length <= 104
39
+ * s contains English letters (upper-case and lower-case), digits, and spaces ' '.
40
+ * There is at least one word in s.
41
+ *
42
+ * Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1)
43
+ * extra space?
44
+ ******************************************************************************************************/
45
+
46
+ #include " ../inc/ac.h"
47
+ class Solution
48
+ {
49
+ public:
50
+ string reverseWords (string s)
51
+ {
52
+
53
+ reverse (s.begin (), s.end ());
54
+ int n = s.size ();
55
+ int index = 0 ;
56
+ for (int start = 0 ; start < n; start++)
57
+ {
58
+ if (s[start] != ' ' )
59
+ {
60
+ // Go to begining of the word
61
+ if (index != 0 )
62
+ s[index++] = ' ' ;
63
+
64
+ int end = start;
65
+ // Go to the end of the word
66
+ while (end < n && s[end] != ' ' )
67
+ {
68
+ s[index++] = s[end++];
69
+ }
70
+
71
+ // Reverse the word
72
+ reverse (s.begin () + index - (end - start), s.begin () + index);
73
+
74
+ // Move to the next word
75
+ start = end;
76
+ }
77
+ }
78
+
79
+ s.erase (s.begin () + index, s.end ());
80
+ return s;
81
+ }
82
+ };
83
+
84
+ int main ()
85
+ {
86
+
87
+ string s = " the sky is blue" ;
88
+ cout << Solution ().reverseWords (s) << " \n " ;
89
+ return 0 ;
90
+ }
0 commit comments