Reverse words
来源:互联网 发布:济南行知小学学区划分 编辑:程序博客网 时间:2024/05/22 10:58
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
click to show clarification.
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
值得注意的就是stack的操作,不要用stack.size() 和stack.pop()一起,size 会变!
public String reverseWords(String s) {Stack<String> stack = new Stack<String>();for (int i = 0; i < s.length();) {while (i < s.length() && s.charAt(i) == ' ') {i++;}int j = i;for (; j < s.length() && s.charAt(j) != ' '; j++) {;}stack.add(s.substring(i, j));i = j;} String result = ""; while (!stack.isEmpty()) { //<span style="color:#ff0000;">不要用stack.size()的for循环,因为采用了stack.pop()操作</span>
result = result.isEmpty() ? stack.pop() : result + " " + stack.pop(); }return result;}
0 0
- Reverse words
- Reverse Words
- Problem B. Reverse Words
- Leetcode - Reverse Words
- Reverse words in a string.
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Spring MVC 框架搭建及详解
- MyBatis+Spring 基于接口编程的原理分析
- Volley.jar 制作方法
- 最长回文子串
- DirectX 9.0c游戏开发手记之“龙书”第二版学习笔记之7: Chap9: Color
- Reverse words
- 算法学习之排序算法:插入排序(直接插入排序、折半插入排序、2-路插入排序)
- 关于编程学习的七点思索
- 各种开源协议介绍 BSD、Apache Licence、GPL V2 、GPL V3 、LGPL、MIT
- 8种Nosql数据库系统对比
- 算法学习之排序算法:冒泡排序
- Redhat-linux常识
- find命令的常用
- 自己写的一个快速排序