1 Star 1 Fork 0

jiexingwei/C++算法编程题(剑指offer)

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
翻转单词序列.cpp 1.58 KB
一键复制 编辑 原始数据 按行查看 历史
jiexingwei 提交于 2020-03-24 23:32 +08:00 . 剑指offer c++s实现
链接:https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tqId=11197&tPage=3&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
来源:牛客网
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事CatFish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
class Solution {
public:
string ReverseSentence(string str) {
//这道题先把整体反转,然后再把每个单词反转,时间复杂度为O(n^2),空格个数都不能少
string res;
if (str.empty())
{
return res;
}
reverse(str.begin(), str.end());
int j = 0;
for (int i = 0; i < str.size(); i++)
{
if (str[i] != ' ')
{
string temp;
for (j = i; j < str.size() && str[j] != ' '; j++) //记录每个单词
{
temp += str[j];
}
reverse(temp.begin(), temp.end());
res = res + temp;
while(j < str.size() && str[j] == ' ') //继续复制空格数
{
res += ' ';
j++;
}
i = --j;
}
else
{
res += str[i];
}
}
return res;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/jie_xing_wei/code_c_algorithm.git
git@gitee.com:jie_xing_wei/code_c_algorithm.git
jie_xing_wei
code_c_algorithm
C++算法编程题(剑指offer)
master

搜索帮助