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

本题牛客网地址

本题代码的github地址

本系列文章的索引地址

# 题目

# 思路

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

# 代码

#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;
}

最新文章

  1. 到底应该选择那种Linux.NET的部署方式?
  2. Redis的5种数据结构
  3. DAY1 linux 50条命令
  4. malloc钩子和内存泄漏工具mtrace、Valgrind
  5. Bootstrap页面布局11 - BS表单
  6. python 基础学习(字典对象,set对象)
  7. vs2005升级到vs2010相关问题
  8. CKEditor + CKFinder 实现编辑上传图片配置 (二)
  9. 【译】在Asp.Net中操作PDF - iTextSharp - 利用列进行排版
  10. yum 简介及使用 安装、删除
  11. 初识Selenium(二)
  12. Springboot学习记录1--概念介绍以及环境搭建
  13. react-native入坑随笔(持续更新中)
  14. fpc软排线焊接
  15. Android连接服务器端的Socket
  16. 基于consul高可用
  17. MongoDB一键安装
  18. 【Redis】4、Redis学习资料
  19. 「2017 山东一轮集训 Day5」距离
  20. 每月IT摘录201805

热门文章

  1. Nginx配置X-Forwarded-Proto
  2. 爬虫之Handler处理器 和 自定义Opener
  3. [Pytorch]Pytorch 保存模型与加载模型(转)
  4. java.lang.IllegalArgumentException的解决方法
  5. LA 5846 霓虹灯广告牌(单色三角形问题)
  6. UML类图概述、设计模式
  7. HIVE学习(待更新)
  8. LeetCode 454. 4Sum II
  9. proxy-target-class 作用
  10. Python 序列化pickle/cPickle模块整理