Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 26, 2017 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/bf87c1d59a393f6b8233fd886003b3a8 to your computer and use it in GitHub Desktop.
Save jianminchen/bf87c1d59a393f6b8233fd886003b3a8 to your computer and use it in GitHub Desktop.
reverse words - code review C++ code. Dec. 25, 2017 6:00 PM
#include <iostream>
#include <vector>
using namespace std;
void reverse(vector<char> & arr,int start,int end);
vector<char> reverseWords( const vector<char>& arr ) // "a b cd"
{
// your code goes here
vector<char> copy;
vector<int> index;
for(int i = 0; i < arr.size(); i ++){
copy.push_back(arr[i]);
}
reverse(copy,0,copy.size()-1);
index.push_back(-1);
for(int i = 0; i < copy.size(); i ++){
if(copy[i] == ' '){
index.push_back(i);
}
}
if(index.size() == 1){
return arr;
}
// reverse the word
int j = 0;
while(j <= index.size() - 2){
reverse(copy,index[j]+1,index[j+1]-1);
j++;
}
reverse(copy,index[j]+1,copy.size()-1);
return copy;
}
void reverse(vector<char> & arr,int start,int end){
while(end > start){
swap(arr[start++],arr[end--]);
}
}
int main() {
vector<char> v = {'a',' ','b',' ','c','d'};
vector<char> r = reverseWords(v);
for(int i = 0; i < r.size(); i ++){
cout << r[i] << endl;
}
return 0;
}
@jianminchen
Copy link
Author

Ask the peer to remove extra space for word reverse, use O(1) space instead of O(n).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment