Created
December 26, 2017 02:57
-
-
Save jianminchen/bf87c1d59a393f6b8233fd886003b3a8 to your computer and use it in GitHub Desktop.
reverse words - code review C++ code. Dec. 25, 2017 6:00 PM
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 <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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ask the peer to remove extra space for word reverse, use O(1) space instead of O(n).