186. Reverse Words in a String II

Posted panini

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了186. Reverse Words in a String II相关的知识,希望对你有一定的参考价值。

题目:

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?

链接:  http://leetcode.com/problems/reverse-words-in-a-string-ii/

6/21/2017

3ms, 39%

注意不要遗漏了最后一个reverse,end都是exclusive的,这样跟其他库函数类似。

 1 public class Solution {
 2     public void reverseWords(char[] s) {
 3         if (s == null || s.length == 0) {
 4             return;
 5         }
 6         reverse(s, 0, s.length);
 7         int start = 0;
 8         for (int i = 1; i < s.length; i++) {
 9             if (s[i] == ‘ ‘) {
10                 reverse(s, start, i);
11                 start = i + 1;
12             }
13         }
14         reverse(s, start, s.length);
15         return;
16     }
17     private void reverse(char[] s, int start, int end) {
18         for (int i = start, j = end - 1; i < j; i++, j--) {
19             char tmp = s[i];
20             s[i] = s[j];
21             s[j] = tmp;
22         }
23         return;
24     }
25 }

更多讨论

https://discuss.leetcode.com/category/194/reverse-words-in-a-string-ii

以上是关于186. Reverse Words in a String II的主要内容,如果未能解决你的问题,请参考以下文章

186. Reverse Words in a String II

leetcode 186. Reverse Words in a String II 旋转字符数组 ---------- java

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

Reverse Words in a String

151. Reverse Words in a String

Leetcode 151. Reverse Words in a String