Happyleetcode1:reverse Words in a string topic description:
Topic thinking:
- Create an array that stores one word per array.
- Output the array in reverse, followed by a space after each word output.
Topic Problem Solving Code python
Class Solution:
# @param s, a string
# @return A string
def reversewords (self, s):
Slist=[]
Slist=s.split ()
For I in range (len (slist)/2):
Slist[i],slist[len (slist) -1-i]=slist[len (slist) -1-i],slist[i]
Return '. Join (Slist)
C++
Class Solution {
Public
void Reversewords (String &s) {
if (S.empty ())
Return
Remove heading and trailing spaces
int i = 0;
while (I<s.size () && s[i] = = ")
i++;
if (i = = S.size ())
{
s = "";
Return
}
Int J = s.size ()-1;
while (j>=0 && s[j] = = ")
j--;
if (j = =-1)
{
s = "";
Return
}
s = s.substr (i,j-i + 1);
size_t pos = 0;
Vector<string> STRs;
size_t begin = 0;
while (Begin < S.size ())
{
pos = s.find_first_of (", begin);
if (pos = = begin)
{
begin++;
Continue
}
else if (pos! =-1)
Strs.push_back (S.substr (Begin,pos-begin));
else//pos = =-1, the end
{
Strs.push_back (S.substr (Begin,s.size ()-1-begin + 1));
Break
}
Begin = pos + 1;
}
String ans;
for (int i = Strs.size ()-1; i > 0; i--)
{
Ans + = strs[i];
Ans + = "";
}
Ans + = strs[0];
s = ans;
}
};
Post-Title Summary
- ". Join (Slist) is a divine expression of a list-to-string.
Official answers
One simple approach was a two-pass Solution:first pass to split the string by spaces into an array of words and then second P Extract the words in reversed order.
We can do better in One-pass. While iterating the string in reverse order, we keep track of a word ' s begin and end position. When we is at the beginning of a word, we append it.
HappyLeetcode1 Reverse Words in a String