首页 > 学院 > 开发设计 > 正文

Leetcode: Reverse Words in a String II

2019-11-14 23:06:30
字体:
来源:转载
供稿:网友
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 ' '

 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 }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表