Reverse Words in a String —— Leetcode
2015-09-09 18:29
465 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
class Solution {
public:
void reverseWords(string &s) {
if(s.empty()) {
s.clear();
return ;
}
int i = 0;
stack<string> st;
while(i<s.size()) {
//将i置于每个单词首字母位置
while(s[i]==' ') i++;
if(i==s.size()) break;
//将j置于单词末尾处后一位
int j = i;
while(s[j]!=' ' && j<s.size()) j++;
//将该单词添加入stack
st.push(s.substr(i, j-i));
i = j;
}
//翻转后的单词
s.clear();
while(!st.empty()) {
s += st.top()+" ";
st.pop();
}
s = s.substr(0, s.size()-1);
}
};
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
class Solution {
public:
void reverseWords(string &s) {
if(s.empty()) {
s.clear();
return ;
}
int i = 0;
stack<string> st;
while(i<s.size()) {
//将i置于每个单词首字母位置
while(s[i]==' ') i++;
if(i==s.size()) break;
//将j置于单词末尾处后一位
int j = i;
while(s[j]!=' ' && j<s.size()) j++;
//将该单词添加入stack
st.push(s.substr(i, j-i));
i = j;
}
//翻转后的单词
s.clear();
while(!st.empty()) {
s += st.top()+" ";
st.pop();
}
s = s.substr(0, s.size()-1);
}
};
相关文章推荐
- 黑马程序员_java01_基本知识点
- Android客户端支付宝支付
- Qt5.4.1移植到arm——Linuxfb篇
- 【more effective c++读书笔记】【第5章】技术(7)——让函数根据一个以上的对象类型来决定如何虚化(1)
- 颜色渐变的算法
- 【more effective c++读书笔记】【第5章】技术(7)——让函数根据一个以上的对象类型来决定如何虚化(1)
- 自己平常用的广告滚动
- Android入门之网络图片查看器
- 在Activity启动过程中如何任务栈的栈顶是否是将要启动的Activity的实例
- popwindwo遇到.9.png出现bug
- requestDisallowInterceptTouchEvent的用法
- Lua中的loadfile、dofile、require详解
- 用指针方法排序数组
- 代码生成 避免重复劳动 省时省力
- 简单CSS线性渐变颜色
- 用指针方法排序数组
- cornerstone忽略显示.DS_Store文件
- 菜鸟级springmvc+spring+mybatis整合开发用户登录功能(下)
- leetcode_Permutations II
- iOS block里的self