Last active
August 13, 2016 09:47
-
-
Save itayB/3769ba03f310f7e7e46160a6aa8986d0 to your computer and use it in GitHub Desktop.
Write a program to reverse the words order in a sentence (without using additional space)
This file contains 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 <string> | |
void swap(char* a, char* b) { | |
char temp = *a; | |
*a = *b; | |
*b = temp; | |
} | |
void reverse_chars(char* str, int start, int end) { | |
// TODO: add nullptr validation | |
while (start < end) { | |
swap(&str[start],&str[end]); | |
start++; | |
end--; | |
} | |
} | |
void reverse_words(char* str) { | |
if (str == nullptr || strlen(str) == 0) | |
return; | |
int length = strlen(str); | |
reverse_chars(str, 0, length-1); | |
int start_index = 0; | |
int end_index = 0; | |
for(int i=0 ; i <= length ; i++) { | |
if (str[i] == ' ' || i == length) { | |
end_index = i - 1; | |
reverse_chars(str, start_index, end_index); | |
start_index = i + 1; | |
} | |
} | |
} | |
void test(char* str) { | |
printf("Before: %s, ", str); | |
reverse_words(str); | |
printf("After: %s\n", str); | |
} | |
int main() { | |
char str[100]; | |
strcpy(str,""); | |
test(str); | |
strcpy(str,"Aa"); | |
test(str); | |
strcpy(str,"Aa Bb"); | |
test(str); | |
strcpy(str,"Aa Bb Cc"); | |
test(str); | |
strcpy(str,"Aa1 Bb2 Cc3"); | |
test(str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment