首页 > 代码库 > leetcode 186. Reverse Words in a String II 旋转字符数组 ---------- java
leetcode 186. Reverse Words in a String II 旋转字符数组 ---------- java
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?
1、刚开始的想法是找到第一个和最后一个单词,然后交换他们两个,但是遇到的问题是两个单词长度不一致的时候会很麻烦,就需要将剩余的字符串整个进行移动,麻烦,且效率很低。
2、参考了discuss,发现很其实想法很简单,就是分两步:第一步就是把整个字符串倒过来,第二步就是再翻回来之后再把每个单词反转一次就好了。
public class Solution { public void reverseWords(char[] s) { int len = s.length; reverse(s, 0, len - 1); int start = 0; for (int i = 0; i < len - 1; i++){ if (s[i] == ‘ ‘){ reverse(s, start, i - 1); start = i + 1; } } reverse(s, start, len - 1); } private void reverse(char[] s, int start, int end){ while (start < end){ char ch = s[start]; s[start] = s[end]; s[end] = ch; start++; end--; } } }
leetcode 186. Reverse Words in a String II 旋转字符数组 ---------- java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。