151. Reverse Words in a String (Inplace) -- unfinished! Write the copy part.

class Solution { public: void reverseHelper(string & s, size_t start, size_t end){ // a helper function to reverse a word, inplace. // start is the start of the word, end is the end of the word in the original string. Inclusive size_t i = start; size_t j = end; while(i < j){ auto tmp = std::move(w[i]); s[i] = s[j]; s[j] = tmp; i++; j--; } } void reverseWords(string &s) { size_t i = 0; while(true){ while(s[i] == ' ' && i < s.size()-1) i++; // shift i to the beginning of the first word size_t j = i; while(s[j] != ' ' && j < s.size()-1) j++; // detect a word! reverseHelper(s, i, j); i = j+1; if (i > s.size()-1) break; } } };
Algorithm:

- For every detected word, reverse it.
- Then reverse the whole string.

http://www.ardendertat.com/2011/10/31/programming-interview-questions-12-reverse-words-in-a-string/

We’ll overwrite the string in-place.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.