首页 > 其他 > 详细

Leetcode: Reverse Words in a String II

时间:2015-03-01 08:52:07      阅读:247      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!