File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
algorithms/cpp/reverseWordsInAString Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 2424**********************************************************************************/
2525
2626#include < ctype.h>
27+ #include < stdio.h>
28+ #include < stdlib.h>
29+ #include < string.h>
2730#include < iostream>
2831#include < string>
2932#include < vector>
33+ #include < algorithm> // for std::reverse
3034using namespace std ;
3135
3236void reverseWords (string &s) {
@@ -100,6 +104,53 @@ void reverseWords2(string &s) {
100104 s.swap (result);
101105}
102106
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+ ws = p;
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+
103154main ()
104155{
105156 string s;
@@ -113,4 +164,5 @@ main()
113164 s=" i love cpp" ;
114165 reverseWords (s);
115166
167+ test ();
116168}
You can’t perform that action at this time.
0 commit comments