1. 程式人生 > >186. Reverse Words in a String II

186. Reverse Words in a String II

defined pro etc pan log without rate null target

題目:

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