【剑指offer】翻转单词顺序,C++实现
2024-10-01 17:05:53
原创博文,转载请注明出处!
# 题目
# 思路
两次翻转,第一次翻转整个句子,第二次翻转每个单词(单词之间用逗号隔开)
# 代码
#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;
}
最新文章
- 到底应该选择那种Linux.NET的部署方式?
- Redis的5种数据结构
- DAY1 linux 50条命令
- malloc钩子和内存泄漏工具mtrace、Valgrind
- Bootstrap页面布局11 - BS表单
- python 基础学习(字典对象,set对象)
- vs2005升级到vs2010相关问题
- CKEditor + CKFinder 实现编辑上传图片配置 (二)
- 【译】在Asp.Net中操作PDF - iTextSharp - 利用列进行排版
- yum 简介及使用 安装、删除
- 初识Selenium(二)
- Springboot学习记录1--概念介绍以及环境搭建
- react-native入坑随笔(持续更新中)
- fpc软排线焊接
- Android连接服务器端的Socket
- 基于consul高可用
- MongoDB一键安装
- 【Redis】4、Redis学习资料
- 「2017 山东一轮集训 Day5」距离
- 每月IT摘录201805