Given an input string, reverse the string word by word.

Example:

Input: "the sky is blue",
Output: "blue is sky the".
Note:

A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.

思路

1.  split by a single or multiple spaces, making sure remove leading or trailing spaces

2. to reverse,  traverse the input from right to left,  append each item into StringBuilder

代码

 public class Solution {
public String reverseWords(String s) {
// corner case
if(s == null || s.length() == 0) return "";
// s.trim() 去除leading or trailing spaces
// s.split("\\s+")根据a single or multiple spaces 来split字符串
String[] words = s.trim().split("\\s+");
// use StringBuilder to save result
StringBuilder sb = new StringBuilder();
// to reverse, from right to left
for(int i = words.length-1; i >= 0; i--){
sb.append(words[i]+" ");
}
// 确保结果中去除了leading or trailing spaces
return sb.toString().trim();
}
}

最新文章

  1. Postgresql 简单配置 (ubuntu server 14.04.3)
  2. Linux下三个密码生成工具
  3. vim的树形菜单NERDTREE的设置
  4. WinForm程序关闭窗体后杀死进程
  5. UNITY3d在移动设备上的一些优化实战(一)-概述
  6. 如何为自己的windows 8系统的电脑更换锁屏壁纸
  7. ExtJs TreePanel 使用帮助
  8. Hive Experiment 2(表动态分区和IDE)
  9. Ubuntu下面配置问题
  10. 我的第一款windows phone软件
  11. 使用原生JavaScript
  12. Oracle数据库表的备份和数据表的删除操作
  13. 更新证书错误Code Sign error: Provisioning profile ‘XXXX'can't be found
  14. [jobdu]矩形覆盖
  15. 子网/ip/子网掩码
  16. vs/windows程序找不到入口点cuvidGetDecodeStatus于AppDecGL.exe动态链接库上
  17. Android:谈一谈安卓应用中的Toast情节(基础)
  18. QT日志系统
  19. Spring Cloud+Dubbo对Feign进行RPC改造
  20. Python装饰器基础及运行时间

热门文章

  1. pycharm 直接删掉数据表之后,makemigration和migrate 之后,数据库中依然没有生成数据表的问题
  2. ConcurrentModificationException原因及排除
  3. python中序列化json模块和pickle模块
  4. mysql / pgsql 使用sql语句查询数据库所有表注释已经表字段注释
  5. Structs复习 Action传递参数
  6. JavaScript中的构造函数 renturn
  7. python字典dict的增、删、改、查操作
  8. &符号 (弃用引用传参了,不要用!!)
  9. 头像修改功能 包含ios旋转图片 但是旋转后没遮罩, 正常图片可以显示遮罩 宽高不规则图片没做控制 遮罩框可以拖动
  10. Java的map键值对的用法,map的遍历,Entry对象的使用