码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-151-Reverse Words in s String

时间:2019-02-07 10:53:25      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:ever   nbsp   har   output   note   div   bsp   解题思路   trail   

算法描述:

Given an input string, reverse the string word by word.

Example:  

Input: "the sky is blue",
Output: "blue is sky the".

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

解题思路:先逐词翻转,再整句翻转。注意去除空格。

void reverseWords(string &s, int i, int j){
    while(i < j){
        char temp = s[i];
        s[i++]=s[j];
        s[j--]=temp;        
    }   
}

void reverseWords(string &s){
    int i = 0;
    int j = 0;
    int l = 0;
    int n = s.size();
    int count = 0;
    while(true){
        while(i < n && s[i] ==  ) i++;
        if(i==n) break;
        if(count) s[j++] =  ;
        l=j;
        while(i < n && s[i]!=  ) {s[j]=s[i]; j++; i++;}
        reverseWords(s,l,j-1);
        count++;
    }
    s.resize(j);
    reverseWords(s,0,j-1);
}

 

LeetCode-151-Reverse Words in s String

标签:ever   nbsp   har   output   note   div   bsp   解题思路   trail   

原文地址:https://www.cnblogs.com/nobodywang/p/10354474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!