Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
reverse-words-in-a-string.cpp 745 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-02-22 22:12 +08:00 . Update reverse-words-in-a-string.cpp
// Time: O(n)
// Space: O(1)
class Solution {
public:
void reverseWords(string &s) {
// Reverse the whole string first.
reverse(s.begin(), s.end());
size_t begin = 0, end = 0, len = 0;
while ((begin = s.find_first_not_of(" ", end)) != string::npos) {
if ((end = s.find(" ", begin)) == string::npos) {
end = s.length();
}
// Reverse each word in the string.
reverse(s.begin() + begin, s.begin() + end);
// Shift the word to avoid extra space.
move(s.begin() + begin, s.begin() + end, s.begin() + len);
len += end - begin;
s[len++] = ' ';
}
s.resize(len ? len - 1 : 0);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助