首页 > 代码库 > 186. Reverse Words in a String II
186. 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?
链接: 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。