[leetcode]151. Reverse Words in a String翻转给定字符串中的单词
2024-10-12 00:53:00
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();
}
}
最新文章
- Postgresql 简单配置 (ubuntu server 14.04.3)
- Linux下三个密码生成工具
- vim的树形菜单NERDTREE的设置
- WinForm程序关闭窗体后杀死进程
- UNITY3d在移动设备上的一些优化实战(一)-概述
- 如何为自己的windows 8系统的电脑更换锁屏壁纸
- ExtJs TreePanel 使用帮助
- Hive Experiment 2(表动态分区和IDE)
- Ubuntu下面配置问题
- 我的第一款windows phone软件
- 使用原生JavaScript
- Oracle数据库表的备份和数据表的删除操作
- 更新证书错误Code Sign error: Provisioning profile ‘XXXX'can't be found
- [jobdu]矩形覆盖
- 子网/ip/子网掩码
- vs/windows程序找不到入口点cuvidGetDecodeStatus于AppDecGL.exe动态链接库上
- Android:谈一谈安卓应用中的Toast情节(基础)
- QT日志系统
- Spring Cloud+Dubbo对Feign进行RPC改造
- Python装饰器基础及运行时间
热门文章
- pycharm 直接删掉数据表之后,makemigration和migrate 之后,数据库中依然没有生成数据表的问题
- ConcurrentModificationException原因及排除
- python中序列化json模块和pickle模块
- mysql / pgsql 使用sql语句查询数据库所有表注释已经表字段注释
- Structs复习 Action传递参数
- JavaScript中的构造函数 renturn
- python字典dict的增、删、改、查操作
- &;符号 (弃用引用传参了,不要用!!)
- 头像修改功能 包含ios旋转图片 但是旋转后没遮罩, 正常图片可以显示遮罩 宽高不规则图片没做控制 遮罩框可以拖动
- Java的map键值对的用法,map的遍历,Entry对象的使用