Leetcode Reverse Words in a String
2015-10-11 02:35
453 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Java code:
Reference:
1. https://leetcode.com/discuss/56712/straightforward-java-solution-using-split
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
解题思路:
用trim() 和splite("\\s+")把String 切割成一个一个word, 然后用StringBuilder 重建String. O(n) time and O(n) SpaceJava code:
public String reverseWords(String s) { if( s == null || s.length() == 0 ){ return ""; } String[] splited = s.trim().split("\\s+"); int len = splited.length; StringBuilder sb = new StringBuilder(); for(int i = len-1; i >= 0; i--){ sb.append(splited[i] + " "); } return sb.toString().trim(); }
Reference:
1. https://leetcode.com/discuss/56712/straightforward-java-solution-using-split
相关文章推荐
- Ember.js 入门指南——包裹内容
- java传入相关的时间可以获取这个时间段的星期时间
- Android应用开发性能优化完全分析
- 安卓手机烧内存卡(就是内存卡损坏)的补救办法
- 记惠普javaweb实训周之版本控制系统的实践
- MFC库中CObject
- LXT6架构-linux-x/arch/arm/下的故事(回顾)
- Handler+Looper+MessageQueue深入详解
- 深入浅出MFC学习笔记4--简单而完整:MFC骨干程序
- OpenCV3.0.0在VS2013中的配置(Win7_32位)
- EasyUI弹出窗口实例
- ISO/IEC 9899:2011 条款6.7——声明
- 深入探讨Java的类加载机制
- Leetcode Rotate Array
- 数据结构实践项目——串
- Eclipse desktop
- 20151010 C# 第一篇 变量类型
- poj2488
- linux(centos)下非root用户执行管理命令
- 体积小巧、功能强大的代理工具 -- 3proxy