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--;
            }
        }
    }
  • 相关阅读:
    EFCore数据库迁移命令
    EF基本操作
    EF执行存储过程
    [vue]element-ui使用
    [vue]vue-router的使用
    [vue]使用webpack打包
    [vue]插槽与自定义事件
    [vue]计算属性
    [vue]axios异步通信
    [vue]组件
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6145597.html
Copyright © 2011-2022 走看看