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

原文地址:https://www.cnblogs.com/panini/p/7061523.html