This is one of those problems where the clean idea matters more than the amount of code. For 151. Reverse Words in a String, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are string_split2, join, reverseWords.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01class Solution {
02public:
03 std::vector<std::string> string_split2(std::string str)
04 {
05 // Used to split string around spaces.
06 std::istringstream ss(str);
07 std::vector<std::string> result;
08 std::string word;
09
10 //need to check whether the reading success before using it
11 while(ss >> word){
12 result.push_back(word);
13 }
14
15 return result;
16 }
17
18 template <typename Iter>
19 std::string join(Iter begin, Iter end, std::string const& separator)
20 {
21 std::ostringstream result;
22 result.precision(2); //for floating point
23 if (begin != end)
24 result << *begin++;
25 while (begin != end)
26 //std::fixed : for floating point
27 result << std::fixed << separator << *begin++;
28 return result.str();
29 }
30
31 string reverseWords(string s) {
32 vector<string> tokens = string_split2(s);
33
34 return join(tokens.rbegin(), tokens.rend(), " ");
35 }
36};
Cost