zoukankan      html  css  js  c++  java
  • [LeetCode] Reverse Words in a String II

    Problem Description:

    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?

    Since this problem has guaranteed that the string does not contain all the leading and trailing spaces and all words are separated by a single space, it will be much easier to be solved in space. The idea is to reverse the whole string first. Then we visit the string from left to right, each time we meet a space, we reverse the immediate word before it.

    The code is as follows.

     1 class Solution {
     2 public:
     3     void reverseWords(string &s) {
     4         reverse(s.begin(), s.end());
     5         s += ' ';
     6         int i = 0, j = 0, n = s.length();
     7         while (i < n && j < n) {
     8             while (j < n && s[j] != ' ') j++;
     9             if (j < n) {
    10                 reverseBetween(s, i, j - 1);
    11                 i = j + 1;
    12                 j = i;
    13             }
    14         }
    15         s.resize(n - 1);
    16     }
    17 private:
    18     void reverseBetween(string &s, int i, int j) {
    19         while (i < j)
    20             swap(s[i++], s[j--]);
    21     }
    22 };

    Note that we append a space to the reversed string to facilitate the detection of the last word.

  • 相关阅读:
    滑动拼图
    CentOS8安装中文输入法
    windows+ubuntu 双系统时间不一致的问题
    Goland 2019下载和安装(带破解补丁和汉化包)
    防火墙站名资源脚本
    linux上以服务方式启动程序kestrel
    NLog实践记录
    sqlserver安装ubuntu
    pyspark提交集群任务
    无法打开hadoop的UI页面
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4600353.html
Copyright © 2011-2022 走看看