[LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词 II

时间:2021-07-17 15:49:48

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?

151. Reverse Words in a String 一样,这里要求不能用额外空间,要用in-place完成。

该题假设开头和结尾没有空格,而且单词之间只有一个空格。不需要这些假设也是可以的,就是代码会比较复杂。
思路就是两步走,第一步就是将整个字符串翻转。然后从头逐步扫描,将每个遇到单词再翻转过来。

[注意事项]
1)如果是Java,应该跟面试官指出String是immutable,所以需要用char array来做。
2)follow-up问题:k-step reverse。也就是在第二部翻转的时候,把k个单词看作一个长单词,进行翻转。

Java:

public void reverseWords(char[] s) {  
reverse(s, 0, s.length);
for (int i=0, j=0; j<=s.length; j++) {
if (j==s.length || s[j]==' ') {
reverse(s, i, j);
i = j + 1;
}
}
}

private void reverse(char [] s, int begin, int end) {
for (int i=0; i<(end-begin)/2; i++) {
char temp = s[begin+i];
s[begin+i] = s[end-i-1];
s[end-i-1] = temp;
}
}

Python:

class Solution(object):
def reverseWords(self, s):

def reverse(s, begin, end):
for i in xrange((end - begin) / 2):
s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i]

reverse(s, 0, len(s))
i = 0
for j in xrange(len(s) + 1):
if j == len(s) or s[j] == ' ':
reverse(s, i, j)
i = j + 1

C++:

class Solution {
public:
void reverseWords(string &s) {
int left = 0;
for (int i = 0; i <= s.size(); ++i) {
if (i == s.size() || s[i] == ' ') {
reverse(s, left, i - 1);
left = i + 1;
}
}
reverse(s, 0, s.size() - 1);
}
void reverse(string &s, int left, int right) {
while (left < right) {
char t = s[left];
s[left] = s[right];
s[right] = t;
++left; --right;
}
}
};  

 

类似题目:

[LeetCode] 151. Reverse Words in a String 翻转字符串中的单词

[LeetCode] 557. Reverse Words in a String III 翻转字符串中的单词 III 

All LeetCode Questions List 题目汇总