• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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?

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

(1)reverse the whole array

(2)reverse each subarray seperated by ' '

注意不要忘了reverse最后一个word

 1 public void reverseWords(char[] s) {
 2     // Three step to reverse
 3     // 1, reverse the whole sentence
 4     reverse(s, 0, s.length - 1);
 5     // 2, reverse each word
 6     int start = 0;
 7     int end = -1;
 8     for (int i = 0; i < s.length; i++) {
 9         if (s[i] == ' ') {
10             reverse(s, start, i - 1);
11             start = i + 1;
12         }
13     }
14     // 3, reverse the last word, if there is only one word this will solve the corner case
15     reverse(s, start, s.length - 1);
16 }
17 
18 public void reverse(char[] s, int start, int end) {
19     while (start < end) {
20         char temp = s[start];
21         s[start] = s[end];
22         s[end] = temp;
23         start++;
24         end--;
25     }
26 }

 

posted @ 2015-03-01 07:49  neverlandly  阅读(6591)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3