leetcode 186. Reverse Words in a String II 旋转字符数组 ---------- java
Posted xiaoba1203
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
186. Reverse Words in a String II
186. Reverse Words in a String II
186. Reverse Words in a String II 翻转有空格的单词串 里面不变