---
title: "leetcode__Reverse Words in a String"
author: "xuerenlv"
date: "2014-04-30T14:58:00Z"
tags: []
slug: "leetcode-reverse-words-in-a-string"
draft: false
lastmod: "2014-05-21T10:06:50Z"
id: 2068898
url: "https://xuerenlv.iteye.com/blog/2068898"
---

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

For example,  
Given s = "`the sky is blue`",  
return "`blue is sky the`".

[click to show clarification.](http://oj.leetcode.com/problems/reverse-words-in-a-string/)

总结：这个看人家的。

```
class Solution {
public:
   
    void reverseWords(string &s) {
        string rs;
        for (int i = s.length()-1; i >= 0; ){
            while (i >= 0 && s[i] == ' ') i--;
            if (i < 0) break;
            if (!rs.empty()) rs.push_back(' ');
            
            string t;
            while (i >= 0 && s[i] != ' ') t.push_back(s[i--]);
            reverse(t.begin(), t.end());
            rs.append(t);
        }
        s = rs;
    }
};
```

这个是我的，还没过，继续调试。

```
class Solution {
public:
    void ReverseWord(string &s,int p, int q){
        while(p < q){
            char t = s[p] ;
            s[p++] = s[q] ;
            s[q--] = t ;
        }
    }
    void reverseWords(string &s) {
        int p = 0;
        int q = 0;
        
        while(s[q] != '\0'){
            if(s[q] == ' '){
                ReverseWord(s,p,q-1);
                q++;
                p=q;
            }else{
                q++;
            }
        }
        
        ReverseWord(s,p,q-1);
        ReverseWord(s,0,q-1);
    }
};
```

总结：accepted，要对输入的字符串进行处理

```
class Solution {
public:
    void ReverseWord(string &s,int p, int q){
        while(p < q){
            char t = s[p] ;
            s[p++] = s[q] ;
            s[q--] = t ;
        }
    }
    void reverseWords(string &s) {
        bool flag;
        int p = 0;
        int q = 0;
        
        string str = "";
        for(int i=0;i<s.length();i++)
        {
            flag = false;
            if(s[i] != ' ')
            {
                str += s[i];
            }else if( i-1>=0 && s[i-1] != ' ' ) //前面有
            {
                for(int j=i+1;j<s.length();j++)
                {
                    if(s[j] != ' ')
                    {
                        flag = true;
                        break;
                    }
                }
                if(flag)
                    str += ' ';
            }
        }
        s = str;
        
        while(s[q] != '\0'){
            if(s[q] == ' '){
                ReverseWord(s,p,q-1);
                q++;
                p=q;
            }else{
                q++;
            }
        }
        
        ReverseWord(s,p,q-1);
        ReverseWord(s,0,q-1);
    }
};
```