Last active
December 16, 2015 05:39
-
-
Save mpenkov/5385855 to your computer and use it in GitHub Desktop.
Coding for Interviews: Reverse Words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <assert.h> | |
#define SPACE ' ' | |
void | |
reverse_words(char *sent, size_t len) | |
{ | |
size_t i; | |
size_t start; | |
size_t end; | |
char tmp; | |
/* | |
* Reverse the entire string. | |
*/ | |
for (i = 0; i < len/2; ++i) | |
{ | |
tmp = sent[i]; | |
sent[i] = sent[len-1-i]; | |
sent[len-1-i] = tmp; | |
} | |
/* | |
* Find the first non-space element. | |
*/ | |
for (start = 0; start < end && sent[start] == SPACE; ++start) | |
; | |
/* | |
* Reverse individual words in the string. | |
* Words are delimited by SPACE. | |
*/ | |
while (start < len) | |
{ | |
for (end = start+1; end < len && sent[end] != SPACE; ++end) | |
; | |
for (i = start; i < (start+end)/2; ++i) | |
{ | |
tmp = sent[i]; | |
sent[i] = sent[end-1-i+start]; | |
sent[end-1-i+start] = tmp; | |
} | |
start = end+1; | |
} | |
} | |
int | |
main(int argc, char **argv) | |
{ | |
char *sent = NULL; | |
if (argc == 1) | |
{ | |
char const *tmp = "Coding for Interviews contains too many gifs."; | |
sent = (char *)malloc(sizeof(char)*strlen(tmp)); | |
assert(sent); | |
strcpy(sent, tmp); | |
} | |
else | |
{ | |
sent = (char *)malloc(sizeof(char)*strlen(argv[1])); | |
assert(sent); | |
strcpy(sent, argv[1]); | |
} | |
reverse_words(sent, strlen(sent)); | |
printf("`%s'\n", sent); | |
free(sent); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment