8000
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 2d9734d + 0f33a8d commit 4c6d32fCopy full SHA for 4c6d32f
algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp
@@ -24,9 +24,13 @@
24
**********************************************************************************/
25
26
#include <ctype.h>
27
+#include <stdio.h>
28
+#include <stdlib.h>
29
+#include <string.h>
30
#include <iostream>
31
#include <string>
32
#include <vector>
33
+#include <algorithm> // for std::reverse
34
using namespace std;
35
36
void reverseWords(string &s) {
@@ -100,6 +104,53 @@ void reverseWords2(string &s) {
100
104
s.swap(result);
101
105
}
102
106
107
+
108
+// C solution in O(1) space
109
+void reverse(char *b, char *e) {
110
+ for (--e; e - b > 0; b++, e--) {
111
+ char t = *b;
112
+ *b = *e;
113
+ *e = t;
114
+ }
115
+}
116
117
+void reverseWords(char *s) {
118
+ char *p = s, *ws = NULL, *last = s;
119
120
+ while (*p && *p == ' ') p++; // skip leading space
121
+ ws = p;
122
123
+ for ( ; *p; p++) {
124
+ while (*p && *p != ' ') p++; // find word end
125
126
+ reverse(ws, p);
127
+ strncpy(last, ws, p-ws);
128
+ last += (p-ws);
129
130
+ while (*p && *p == ' ') p++; // for next word
131
132
133
+ if (*p == '\0') break;
134
+ *last++ = ' ';
135
136
+ reverse(s, last);
137
+ *last = '\0';
138
139
140
+void test() {
141
+#define TEST(str) do { \
142
+ char* s = strdup(str); \
143
+ printf("\"%s\" => ", s); \
144
+ reverseWords(s); \
145
+ printf("\"%s\"\n\n", s); \
146
+ free(s); \
147
+ } while (0)
148
149
+ TEST(" the blue sky is blue ");
150
+ TEST(" ");
151
152
153
103
154
main()
155
{
156
string s;
@@ -113,4 +164,5 @@ main()
164
s="i love cpp";
165
reverseWords(s);
166
167
+ test();
168