【剑指offer】翻转单词顺序,C++实现

原创博文,转载请注明出处!

本题牛客网地址

本题代码的github地址

本系列文章的索引地址

# 题目

image

# 思路

      两次翻转,第一次翻转整个句子,第二次翻转每个单词(单词之间用逗号隔开)

 

# 代码

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string ReverseSentence(string str)
    {
        // 特殊输入
        int len=str.length();
        if(len==0) return "";

        // 使用翻转函数翻转整个句子
        Reverse(str,0,len-1);
        cout<<"句子翻转"<<endl;
        cout<<str<<endl;

        // 寻找单词并使用翻转内函数翻转单词
        int i=0;//辅助变量
        int j=0;//辅助变量

        while(i<len)
        {
            // 寻找单词开头
            if(str[i]==' ')
            {
                i++;
                j++;
            }

            // 寻找单词结尾
            if(str[j]!=' ' && str[j]!='\0')
            {
                j++;
            }
            else
            {
                Reverse(str,i,--j);
                i=++j;
            }
            cout<<"i="<<i<<endl;
            cout<<"j="<<j<<endl;
            cout<<str<<endl;
        }
        return str;
    }

    // 翻转函数
    void Reverse(string &str,int pstart,int pend)
    {
        while(pstart < pend)
        {
            char temp=str[pstart];
            str[pstart]=str[pend];
            str[pend]=temp;

            pstart++;
            pend--;
        }
    }
};
int main()
{
    string str = "I am a student.";
    Solution solution;
    solution.ReverseSentence(str);
    return 0;
}
posted @ 2018-05-03 08:58  wanglei5205  阅读(1419)  评论(0编辑  收藏  举报
levels of contents