公众号:爱写bug(ID:icodebugs)
翻转字符串里的单词
Given an input string, reverse the string word by word.
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
说明:
- 无空格字符构成一个单词。
- 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
- 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
进阶:
请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。
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.
解题思路:
Java 字符串不支持运算符重载,无法用原地解法。 我们将字符串转为字符型数组并用两个指针来解这道题。指针 i 作为原字符串转为字符数组的索引,从右向左移。指针 j 作为新字符数组索引,从左向右赋值得到原数组 count 长度的字符。count记录遇到的字母数量,每次遇到 空格 字符,新数组得到从该空格字符 向右 count 个字符并刷新count 计数。
Java:
class Solution {
public String reverseWords(String s) {
if (s.length(