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--;
            }
        }
    }
  • 相关阅读:
    C++ MFC学习 (二)
    C++ MFC字符转换
    C++ MFC学习 (一)
    Windows.h 文件学习
    Git 学习
    Git 学习
    php压缩文件夹并下载到本地
    接口类型无限级分类
    mysql 共享锁 排它锁
    docker基础命令
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11340353.html
Copyright © 2011-2022 走看看