151. Reverse Words in a String
来源:互联网 发布:懒人js特效 编辑:程序博客网 时间:2024/06/05 03:46
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.
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.
使用正则 \\s+ 分割单词,除了前导的空格,其他的任意长度的空格段都被删除。前导的空格分割后在数组里是一个空串,特殊处理一下即可。
public class Solution { public static String reverseWords(String s){if(s.isEmpty())return "";String[] strs=s.split("\\s+");StringBuilder sb=new StringBuilder();int len=strs.length;if(len>0){for(int i=0,j=len-1;i<len;i++,j--){if(strs[j].length()<1)continue;sb.append(strs[j]);sb.append(' ');}sb.deleteCharAt(sb.length()-1);}return sb.toString();}}
0 0
- LeetCode 151. Reverse Words in a String
- LeetCode 151. Reverse Words in a String
- [LeetCode]151.Reverse Words in a String
- 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
- 151. Reverse Words in a String
- 151. Reverse Words in a String
- 151. Reverse Words in a String
- [leetcode]151. Reverse Words in a String
- 151. Reverse Words in a String
- 151. Reverse Words in a String
- LeetCode 151. Reverse Words in a String
- Leetcode 151. Reverse Words in a String
- 151. Reverse Words in a String
- LeetCode *** 151. Reverse Words in a String
- LeetCode-151.Reverse Words in a String
- 在屏幕中显示下拉表框
- 010-字符个数统计
- 递归打印一个数所有加和的方式
- jQuery $.ajax()通过本地服务器访问到远程服务器,解决远程问题。
- Spark中使用Java编程的常用方法
- 151. Reverse Words in a String
- 织梦CMS5.7版自动给图片添加alt属性的方法
- hdu1885Key Task (BFS+状态压缩)
- JAVA学习总结二十七
- 说文解字(二)
- css3 动画
- 织梦DEDECMS教程:去除列表页文章标题加粗标签
- Trailing Zeroes (III)<二分>
- 基于总变差模型的纹理图像中图像主结构的提取方法