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

    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?

    思路:这题比另一个reverse words要简单,因为不存在多余空格的问题。

    因此in-place方法很简单,先把整个字符串反转,然后依次把字符串中的每个单词再反转一次。

     1 class Solution {
     2 public:
     3     void reverseWords(string &s) {
     4         int l = 0, r = s.size() - 1;
     5         while (l < r)
     6             swap(s[l++], s[r--]);
     7         for (int i = 0, n = s.size(); i < n;)
     8         {
     9             for (r = i + 1; r < n && s[r] != ' '; r++);
    10             l = i, r--;
    11             i = r + 2;
    12             while (l < r)
    13                 swap(s[l++], s[r--]);
    14         }
    15     }
    16 };
  • 相关阅读:
    DOM节点的创建
    js中css样式
    js中面向对象
    js
    this是什么!
    事件
    Dom
    逻辑运算和作用域的问题
    Json
    数组
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5160295.html
Copyright © 2011-2022 走看看