跳至主要内容

151. Reverse Words in a String

class Solution {
public:
string reverseWords(string s)
{
// Create a stringstream object to help with splitting the string
// Clear the input string to reuse it for the result
// Variable to store each word
// Loop through each word separated by spaces in the stringstream
while()
{
// Skip empty tokens (extra spaces)
// If this is the first word added to the result string
// Initialize the result string with the first word
// For subsequent words
// Prepend the word to the result string
}
// Return the result string with words reversed
}
};
  • Use >>
class Solution {
public:
string reverseWords(string s)
{
stringstream ss(s);
string token;
s = "";
while (ss >> token)
{
s = token + ' ' + s;
}
return s.substr(0, s.size() - 1);
}
};
  • T: O(N)O(N)

  • S: O(N)O(N)

  • Use >>

class Solution {
public:
string reverseWords(string s)
{
stringstream ss(s);
s = "";
string token;
while(is >> token)
{
s = (s.empty() ? token : token + " " + s);
}
return s;
}
};
  • T: O(N)O(N)

  • S: O(N)O(N)

  • Use getline

class Solution {
public:
string reverseWords(string s)
{
stringstream ss(s);
s = "";
string token;
while(getline(ss, token, ' '))
{
if(token.empty()) continue;
if(s.empty())
{
s = token;
}
else
{
s = token + ' ' + s;
}
}
return s;
}
};
  • T: O(N)O(N)
  • S: O(N)O(N)