1. Split, Reverse Each Word, and Join
Intuition
Split the sentence s by space into a list of word strings. Reverse each word string using two pointers or slicing. Join all reversed words with a single space delimiter.
When to apply: Basic functional formulation in modern languages.
Algorithm
- Split
sby' 'into word arraywords. - For each word in
words, reverse its characters. - Join
wordswith' '. - Return result.
Split, Reverse Each Word, and Join Trace
2 of 2 questions left todayObservation: Split input string s = "Let's take" by space delimiter ' '
Observation: Split input string s = "Let's take" by space delimiter ' '.
Decision: Yields array ["Let's", "take"] of length 2.
Invariant: Preserves original word ordering.
#include <iostream>#include <string>#include <vector>#include <sstream>#include <algorithm> class Solution {public: std::string reverseWords(std::string s) { std::stringstream ss(s); std::string word; std::string res = ""; while (ss >> word) { std::reverse(word.begin(), word.end()); if (!res.empty()) res += " "; res += word; } return res; }}; int main() { Solution sol; std::cout << sol.reverseWords("Let's take LeetCode contest") << std::endl; // "s'teL ekat edoCteeL tsetnoc" std::cout << sol.reverseWords("Mr Ding") << std::endl; // "rM gniD" return 0;}Time & Space Complexity
- Time complexity:
O(N)— Splits and joins N characters across new string allocations. - Space complexity:
O(N)
Why Brute Force Doesn't Scale:
In-place two-pointer reversal avoids intermediate substring allocations.
Operates with O(1) auxiliary variables.