C solution for "Reverse Words in a String", in O(1) space
This commit is contained in:
parent
174e8aadb5
commit
239694cd9c
@ -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) {
|
||||
@ -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;
|
||||
@ -113,4 +164,5 @@ main()
|
||||
s="i love cpp";
|
||||
reverseWords(s);
|
||||
|
||||
test();
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user