C++中的字符串反转

jos*_*osh 7 c c++ string

我试图通过保持下面的空格来颠倒句子中单词的顺序.

[this is my test    string] ==> [string test my is    this]
Run Code Online (Sandbox Code Playgroud)

我一步一步地做了,

[this is my test    string] - input string
[gnirts    tset ym si siht] - reverse the whole string - in-place
[string    test my is this] - reverse the words of the string - in-place
[string test my is    this] - string-2 with spaces rearranged
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以做到这一点?是否也可以在最后一步就地进行?

cod*_*ict 5

你的方法很好.但另外你也可以这样做:

  • 继续扫描输入的单词和空格
  • 如果你找到一个单词将其推入堆栈 S
  • 如果您发现空格将队列中的空格数排入队列 Q

完成此操作后N,堆栈中将出现单词和N-1队列中的数字.

While stack not empty do
 print S.pop
 if stack is empty break
 print Q.deque number of spaces
end-while
Run Code Online (Sandbox Code Playgroud)