题目描述

牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

 

class Solution {
public:
    //void swap()
    
    void Reversesub(string &str,int a,int b){
        while(a<b)
            swap(str[a++],str[b++]);
    }
    
    string ReverseSentence(string str) {
        int n=str.size();
        Reversesub(str,0,n);
        
        int i=0;
        int a=0,b=0;
        while(i<n) {
            while(i<n && str[i]==' ')
                i++;
            a=b=i;
            while(i<n && str[i]!=' ') {
                i++;
                b++;
            }
            Reversesub(str,a,b-1);
        }
        return str;
    }
};

  

不通过
您的代码已保存
段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
 
原来是部分程序写错。
class Solution {
public:
    //void swap()
    
    void Reversesub(string &str,int a,int b){
        while(a<b)
            swap(str[a++],str[b--]);
    }
    
    string ReverseSentence(string str) {
        int n=str.size();
        Reversesub(str,0,n-1);
        
        int i=0;
        int a=0,b=0;
        while(i<n) {
            while(i<n && str[i]==' ')
                i++;
            a=b=i;
            while(i<n && str[i]!=' ') {
                i++;
                b++;
            }
            Reversesub(str,a,b-1);
        }
        return str;
    }
};

  

 
 
 
 
class Solution {
public:
void ReverseWord(string &str, int s, int e)
    {
        while(s < e)
            swap(str[s++], str[e--]);
    }
 
    string ReverseSentence(string str) {
        ReverseWord(str, 0, str.size() - 1); //先整体翻转
        int s = 0, e = 0;
        int i = 0;
        while(i < str.size())
        {
            while(i < str.size() && str[i] == ' ') //空格跳过
                i++;
            e = s = i; //记录单词的第一个字符的位置
            while(i < str.size() && str[i] != ' ') //不是空格 找单词最后一个字符的位置
            {
                i++;
                e++;
            }
            ReverseWord(str, s, e - 1); //局部翻转
         }
        return str;
    }
}; 

  

posted on 2017-08-23 12:13  王小东大将军  阅读(130)  评论(0编辑  收藏  举报