LeetCode 186.Reverse Words in a String II

来源:互联网 发布:淘宝泰国签证可靠吗 编辑:程序博客网 时间:2024/06/06 03:24

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?

s思路:
1. 这是一道老题。容易想到的方法是,two-pass: 第一次遍历,把整个string reverse,得到”eulb si yks eht”;第二次遍历,对第一次遍历的结果中的每个单词做reverse。所以,可以写一个reverse的函数来负责两轮的reverse操作。

void reverse(string&s, int left, int right){    while(left<right){        swap(s[left],s[right]);        left++;        right--;    }}void reverseWords(string &s) {    //    //pass one    reverse(s,0,s.size()-1);    //pass two    int left=0;    for(int right=0;right<s.size();right++){        if(right+1==s.size()||s[right+1]==""){            reverse(s.substr(left,right-left+1),left,right);            left=right+2;        }       }}
0 0