zoukankan      html  css  js  c++  java
  • 186. Reverse Words in a String II

    Given an input string , reverse the string word by word. 

    Example:

    Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
    Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

    Note: 

    • A word is defined as a sequence of non-space characters.
    • The input string does not contain leading or trailing spaces.
    • The words are always separated by a single space.

    Follow up: Could you do it in-place without allocating extra space?

    two pointers

    time: O(n), space: O(1)

    class Solution {
        public void reverseWords(char[] s) {
            reverse(s, 0, s.length - 1);
            int i = 0, j = 0;
            while(j < s.length) {
                if(s[j] == ' ') {
                    reverse(s, i, j - 1);
                    j++;
                    i = j;
                } else {
                    j++;
                }
            }
            reverse(s, i, j - 1);
        }
        
        private void reverse(char[] c, int i, int j) {
            while(i < j) {
                char tmp = c[i];
                c[i] = c[j];
                c[j] = tmp;
                i++;
                j--;
            }
        }
    }
  • 相关阅读:
    虚拟机virtualBox
    在scala命令行中加入类库
    使用git submodule
    Julia1.x安装
    texshop 使用技巧
    vimdiff换行
    双系统磁盘挂载失败
    www.wolframalpha.com
    sublime3激活方法
    实验数据
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11340353.html
Copyright © 2011-2022 走看看