Skip to content

C solution for "Reverse Words in a String", in O(1) space #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 29, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,13 @@
**********************************************************************************/

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // for std::reverse
using namespace std;

void reverseWords(string &s) {
Expand Down Expand Up @@ -100,6 +104,53 @@ void reverseWords2(string &s) {
s.swap(result);
}


// C solution in O(1) space
void reverse(char *b, char *e) {
for (--e; e - b > 0; b++, e--) {
char t = *b;
*b = *e;
*e = t;
}
}

void reverseWords(char *s) {
char *p = s, *ws = NULL, *last = s;

while (*p && *p == ' ') p++; // skip leading space
ws = p;

for ( ; *p; p++) {
while (*p && *p != ' ') p++; // find word end

reverse(ws, p);
strncpy(last, ws, p-ws);
last += (p-ws);

while (*p && *p == ' ') p++; // for next word
ws = p;

if (*p == '\0') break;
*last++ = ' ';
}
reverse(s, last);
*last = '\0';
}

void test() {
#define TEST(str) do { \
char* s = strdup(str); \
printf("\"%s\" => ", s); \
reverseWords(s); \
printf("\"%s\"\n\n", s); \
free(s); \
} while (0)

TEST(" the blue sky is blue ");
TEST(" ");
}


main()
{
string s;
Expand All @@ -113,4 +164,5 @@ main()
s="i love cpp";
reverseWords(s);

test();
}