Skip to content

Instantly share code, notes, and snippets.

@jizhilong
Created October 27, 2013 12:56
Show Gist options
  • Save jizhilong/7181607 to your computer and use it in GitHub Desktop.
Save jizhilong/7181607 to your computer and use it in GitHub Desktop.
my solution to the classic interview question: "reverse the words in a string , and keep the characters' order within a word unchanged."
/*
* =====================================================================================
*
* Filename: reverse_words.cpp
*
* Description: a program to reverse the words in a sentence.
*
* Version: 1.0
* Created: 10/27/2013 08:21:49 PM
* Revision: none
* Compiler: gcc
*
* Author: Ji.Zhilong (), zhilongji@gmail.com
* Organization: SJTU
*
* =====================================================================================
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::swap;
inline void
reverse_chars(char *arr, int len)
{
if (arr == NULL || len <= 1)
return;
for (int i= 0, j = len - 1; i < j; i++, j--) {
swap(arr[i], arr[j]);
}
}
void
reverse_words(char *arr, int len)
{
if (arr == NULL || len <= 1)
return;
int se[2]; /* storing the start and end indices of words. */
unsigned short k = 0; /* store indices as word start or word end. */
bool spacing = true; /* a flag indicates if the last charcter if a space */
reverse_chars(arr, len);
for (int i = 0; i < len; i++) {
if (spacing ^ arr[i] == ' ') {
spacing = !spacing;
se[k++] = i;
}
if (k == 2) { /* a whole word encounted, normalize it */
reverse_chars(&arr[se[0]], se[1] - se[0]);
k = 0;
}
}
if (!spacing)
reverse_chars(&arr[se[0]], len - se[0]);
}
int
main(int argc, char *argv[])
{
int len = strlen(argv[1]);
reverse_words(argv[1], len);
cout << argv[1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment