Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words in it. (
One way to reverse the order of words is:
string word_reverse(char * data)
{
char c = ' ';
string s=data;
int len=strlen(data);
vector output;
int i=0;
while(s[i]!='\0') {
if(s[i]==c) {
output.push_back(s.substr(0,i));
s=s.substr(i+1,len);
i=0;
continue;
}
i++;
}
output.push_back(s);
s.erase(0,s.length());
string s1;
for(int j=output.size()-1;j>0;j--) {
s1+=output[j];
s1+=" ";
}
s1+=output[0];
return s1;
}
string word_reverse(char * data)
{
char c = ' ';
string s=data;
int len=strlen(data);
vector
int i=0;
while(s[i]!='\0') {
if(s[i]==c) {
output.push_back(s.substr(0,i));
s=s.substr(i+1,len);
i=0;
continue;
}
i++;
}
output.push_back(s);
s.erase(0,s.length());
string s1;
for(int j=output.size()-1;j>0;j--) {
s1+=output[j];
s1+=" ";
}
s1+=output[0];
return s1;
}
Comments
Post a Comment
https://gengwg.blogspot.com/