Leetcode 557. Reverse Words in a String III
You are given a string s. The string contains words separated by spaces. Each word consists of English letters (lower-case and upper-case). You need to return a string where the letters of each word are reversed, but the words themselves remain in the original order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "God Ding"
Output: "doG gniD"
Note:
s contains printable ASCII characters.s only contains English letters and spaces ' '.s.s into words using space as the delimiter.#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
std::string reverseWords(std::string s) {
std::istringstream iss(s);
std::string word;
std::vector<std::string> words;
// Split the string into words
while (iss >> word) {
// Reverse each word and store it in the vector
std::reverse(word.begin(), word.end());
words.push_back(word);
}
// Join reversed words with space
std::ostringstream oss;
for (size_t i = 0; i < words.size(); ++i) {
if (i > 0) {
oss << " ";
}
oss << words[i];
}
return oss.str();
}
int main() {
std::string s = "Let's take LeetCode contest";
std::string result = reverseWords(s);
std::cout << result << std::endl; // Output: "s'teL ekat edoCteeL tsetnoc"
return 0;
}
n is the length of the string as each character is processed once.m is the length of the word. As the sum of all word lengths is equal to n, this step is O(n) in total.n is the length of the final string.Overall, the time complexity of this solution is O(n), where n is the length of the input string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?