Reverse Words in a String II
Given an input string, reverse the string word by word.
Example:
Note:
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do itin-placewithout allocating extra space?
Topics: Two Pointers, String
Analysis
同样是多步翻转+Two Pointer进行逆序、翻转操作。
在void reverseEachWords(char[] str)
中,快指针找到word结尾后的index,满指针指向word的开始第一个index。
Solution
Two-Pointer + Multi-reversal - O(n) time, O(1) space (In-place) - (5ms AC)
This solution (by @siyang3) takes advantage of the conditions in the problem: 1. The input string does not contain leading or trailing spaces. 2. The words are always separated by a single space.
Last updated