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

    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?

    Related problem: Rotate Array

    Runtime: 6ms

     1 class Solution {
     2 public:
     3     void reverseWords(string &s) {
     4         // reverse the entire string
     5         reverseString(s, 0, s.size() - 1);
     6         
     7         // reverse each single word
     8         for (int i = 0; i < s.size(); ) {
     9             int wordEndNext = s.find(" ", i);
    10             // reach to end
    11             if (wordEndNext == s.npos) { 
    12                 reverseString(s, i, s.size() - 1);
    13                 return;
    14             } else {
    15                 reverseString(s, i, wordEndNext - 1);
    16                 i = wordEndNext + 1;
    17             }
    18         }
    19     }
    20     
    21     void reverseString(string &s, int begin, int end) {
    22         for (int i = begin, j = end; i < j; i++, j--)
    23             swap(s[i], s[j]);
    24     }
    25 };
  • 相关阅读:
    预习非数值数据的编码方式
    预习原码补码
    C语言||作业01
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
    C语言|作业12—学期总结
    C语言|博客作业11
    第三章预习
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5895643.html
Copyright © 2011-2022 走看看