码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Reverse Words in a String II

时间:2015-03-01 08:54:48      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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?

这道题要求in-place做法,不能使用extra space, 那么,做法跟Rotate Array那道题非常相似

(1)reverse the whole array

(2)reverse each subarray seperated by ‘ ‘

 1 public class Solution {
 2     public void reverseWords(char[] s) {
 3         if (s.length == 0) return;
 4         reverse(s, 0, s.length-1);
 5         int last = 0;
 6         for (int i=0; i<s.length; i++) {
 7             if (s[i] == ‘ ‘) {
 8                 reverse(s, last, i-1);
 9                 last = i + 1;
10             }
11         }
12     }
13     
14     public void reverse(char[] s, int l, int r) {
15         while (l <= r) {
16             int temp = s[l];
17             s[l] = s[r];
18             s[r] = temp;
19             l++;
20             r--;
21         }
22     }
23 }

 

Leetcode: Reverse Words in a String II

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4306561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!