The problem description is simple enough.
For example, "the sky is blue" => "blue is sky the".
However, this problem is not easy as it seems. We have to deal with the leading and trailing spaces, also the duplicate spaces between to "words" - any visible characters except space could constitute words, such as "^_^" , "<><", "What?!" etc.
One of the tricky way to tackle the problem is use "split" and "join" with Python.
' '.join(raw_input().split(" ")[::-1])
Python is fantastic, but it can hardly satisfy the interviewer.
Usually, we are asked to use a "real programming language" like C++ or Java in the interview. Is there a simple way like the python code above?
The answer is yes.
As we know, Implementing your own trim/strip/join is so annoying, and can bring many potential bugs in your code. But, getline helps you tokenize a string easily with a single delimiter.
class Solution {
public:
void reverseWords(string &s)
{
string token;
istringstream iss(s);
s = "";
while (getline(iss, token, ' ')) {
if (token.empty()) {
continue;
}
s = token + (s.empty()? "":" ") + s;
}
}
};
Oh, well. It is tricky, too. Because it rely too much on build-in functions of C++. But it is much better. :)
If we are forced to write a full version in-place "reverseWords" algorithm all ourselves, what should we do?
class Solution {
public:
void reverseWords(string &s);
private:
void trim(string &s);
};
void Solution::reverseWords(string &s) {
trim(s);
reverse(s. begin(), s.end());
size_t len = s.length();
for (size_t i = 0, pre = 0; i <= len; i++) {
if (isspace(s[i]) || i == len) {
reverse(s.begin() + pre, s.begin() + i);
pre = i + 1;
}
}
}
void Solution::trim(string &s) {
size_t len = s.length();
int p = 0, token = 0;
for (size_t i = 0; i < len; i++) {
if (isspace(s[i])) {
token = 0;
continue;
}
if (!token && p) {
s[p++] = ' ';
}
s[p++] = s[i];
token++;
}
s.erase(p, len);
}
The code is neat because it obeys the "Linus' indentation rule" and simple enough for interviewer to understand quickly.
Linus' Indentation Rule
The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.
EXTENSION:
What should we do if there are multiple delimiters? For example, "The#world*is&gray?"
> boost::split(vector, string, boost::is_any_of("#*&"));
> strpbrk: http://www.cplusplus.com/reference/cstring/strpbrk/