151. Reverse Words in a String
problem description
Given an input string, reverse the string word by word.
Example 1:
Example 2:
Example 3:
Note:
A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up:
For C programmers, try to solve it in-place in O(1) extra space.
algorithm thought
follow up中提到里,如果是c程序员,尝试使用O(1)空间解决。 我寻思cpp程序员应该也行。这里可以利用数组之前的空间,由于这个算法运行之后,字符串大小肯定是小于等于原始字符串大小的。所以,我们们可以在原始字符串上操作,而不需要新开一个字符串。
首先将空格啥的都去掉,得到精简的单词,将单词翻转,最后将得到的字符串翻转
code
algorithm analysis
虽然看起来循环挺多的,但是本质只是遍历了一遍字符串,然后翻转一此,如果长度为n,进行的次数应该是3n,时间复杂度O(n)
Last updated