zoukankan      html  css  js  c++  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-floodfill
    递归和回溯_leetcode131
    递归和回溯_leetcode130
    递归和回溯_leetcode93-经典的回溯题
    递归和回溯_leetcode90
    递归和回溯_leetcode79
    递归和回溯_leetcode78-经典的子集
    知识树杂谈(1)
    Android 设备兼容性(1)
    微信小程序- 生成二维码
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6145597.html
Copyright © 2011-2022 走看看