Reverse Words in a String II
2016-07-07 10:57
681 查看
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string reverword(string);
void reversestr(string&, int, int);
int main()
{
string data[] = { "the sky is blue"};
for (string s : data)
{
reversestr(s, 0, s.size() - 1);
cout << s << endl;
}
for (string s : data)
{
cout << reverword(s) << endl;
}
system("pause");
return 0;
}
string reverword(string str)
{
int len = str.size() - 1;
reversestr(str, 0, len);
cout << str << endl;
string temp;
//下面分割字符串
int i = 0;
int j=0;
// i记录到‘’的位置
//j 记载非‘ ’的位置
while (i < len + 1)
{
if (str[i] != ' ')
{
i++;
if (i == len)
{
reversestr(str, j, i);
}
}
else
{
reversestr(str,j, i-1);
j = i + 1;
i++;
}
}
return str;
}
void reversestr(string& strr, int a, int b)
{
int left = a;
int right = b;
while (left < right)
{
char temp = strr[left];
strr[left] = strr[right];
strr[right] = temp;
left++;
right--;
}
}
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string reverword(string);
void reversestr(string&, int, int);
int main()
{
string data[] = { "the sky is blue"};
for (string s : data)
{
reversestr(s, 0, s.size() - 1);
cout << s << endl;
}
for (string s : data)
{
cout << reverword(s) << endl;
}
system("pause");
return 0;
}
string reverword(string str)
{
int len = str.size() - 1;
reversestr(str, 0, len);
cout << str << endl;
string temp;
//下面分割字符串
int i = 0;
int j=0;
// i记录到‘’的位置
//j 记载非‘ ’的位置
while (i < len + 1)
{
if (str[i] != ' ')
{
i++;
if (i == len)
{
reversestr(str, j, i);
}
}
else
{
reversestr(str,j, i-1);
j = i + 1;
i++;
}
}
return str;
}
void reversestr(string& strr, int a, int b)
{
int left = a;
int right = b;
while (left < right)
{
char temp = strr[left];
strr[left] = strr[right];
strr[right] = temp;
left++;
right--;
}
}
相关文章推荐
- windows的139端口和445端口的区别
- MySQL之索引优化
- spark standalone
- 前端——使footer永远在网页底部的方法
- yii-验证码
- jquery中正则表达式的书写
- nodejs加密Crypto的实例代码
- mac ssh 断开连接
- Qt自已创建打开系统对话框
- android常用工具类库整理
- 论文笔记 | Training Region-based Object Detectors with Online Hard Example Mining
- [转]说说C#的async和await
- objdump命令的使用
- c# 访问oracle数据库
- CocoaPods版本升级
- PAT L2-010. 排座位(并查集)
- yii框架中文件上传
- MinGW下的单步调试
- MFC文件操作学习笔记
- js history使用范例