leetcode解题方案--151--Reverse Words in a String
来源:互联网 发布:linux运维基础知识 编辑:程序博客网 时间:2024/06/03 13:01
听某人的话,从靠后一点的位置开始
这样的话到过年的时候就可以首尾相连了吧
题目
Given an input string, reverse the string word by word.
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.
分析
两个单词之间可能有多个space
字符串左右起始位置可能有space
这道题最简单的方法是用split
但是我没有
思路是用一个栈把string放进去
然后再弹出来。
public static String reverseWords(String s) { System.out.print(Arrays.toString(s.split(" "))); if (s.length()<=0){ return ""; } char[] xx = s.trim().toCharArray(); StringBuffer word = new StringBuffer(""); Stack stack = new Stack<String>(); boolean isWord= true; for (int i = 0; i<xx.length;i++) { if (xx[i] != ' ') { isWord = true; word.append(xx[i]); } else if (xx[i] == ' ' && isWord){ stack.push(word.toString()); isWord = false; word = new StringBuffer(""); } else if (xx[i] == ' '&& !isWord) { } } if (word.toString().length()!=0) { stack.push(word.toString()); } StringBuffer ret = new StringBuffer(""); while (!stack.empty()) { ret.append(stack.pop()); ret.append(" "); } System.out.println(ret); if (ret.length() >= 1) { return ret.toString().substring(0,ret.length()-1); } else{ return ""; } }
阅读全文
0 0
- leetcode解题方案--151--Reverse Words in a String
- LeetCode(151)Reverse Words in a String
- leetcode 151 Reverse Words in a String
- LeetCode: Reverse Words in a String [151]
- [leetcode 151] Reverse Words in a String
- leetcode-151 Reverse Words in a String
- [LeetCode 151]Reverse Words in a String
- Leetcode 151:Reverse Words in a String
- Reverse Words in a String - LeetCode 151
- leetcode[151]:Reverse Words in a String
- LeetCode---(151)Reverse Words in a String
- Leetcode 151 Reverse Words in a String
- LeetCode(151) Reverse Words in a String
- leetcode 151: Reverse Words in a String
- LeetCode 151 Reverse Words in a String
- 【LeetCode-151】Reverse Words in a String
- [LeetCode 151] Reverse Words in a String
- leetcode 151 Reverse Words in a String
- 牛客练习赛7 B 购物(动态规划)
- 迭代器 生成器 装饰器
- php编译安装pecl拓展遇到的问题
- Difference between Steps,Batch size,Epoch in Tensorflow
- AI GOD:1016: 忍者
- leetcode解题方案--151--Reverse Words in a String
- RxJava多播
- ThinkPHP5.1 @[模块/控制器/]操作
- cloudgo-data
- Vue.js学习---脚手架方式搭建vue项目
- 题解
- 【离散数学】1.4集合的运算定律
- 前端用户行为统计
- Ubuntu 简单配置