mattbillock
BAN USER
Comments (2)
Reputation 0
Page:
1
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 vote
Written with a hard-coded string, but can easily be modified to use arguments passed to the function
void reverse_words_in_place()
{
char src[] = "the boy ran";
cout << "Reversing words in place" << endl;
cout << src << endl;
string res("");
char *tok = strtok(src, " ");
while(tok != NULL)
{
string s(tok);
res += string(s.rbegin(), s.rend());
tok = strtok(NULL," ");
if(tok != NULL)
{
res += " ";
}
}
cout << res << endl;
}
Complexity is O(n), and linear on the average length of a word. So if N, with N being the number of words, is larger then the complexity will be O(N), while if m, the average length of words, is larger than N then the complexity will be O(m)
- mattbillock June 07, 2014Page:
1
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.
Looking at this, I can see where it might be N-squared due to the use of the string's += operator, which in C++ has an unspecified complexity but can be up to linear. I may rewrite this to use separate pointers that then swap through each word instead, but I like this solution for its readability.
- mattbillock June 07, 2014