LeetCode-151. Reverse Words in a String
来源:互联网 发布:手机怎么删除淘宝评论 编辑:程序博客网 时间:2024/06/05 18:34
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
输入一个句子然后把每个单词倒序输出。
利用String里的 trim、split函数可以轻松解决。
/** * 返回字符串的副本,忽略前导空白和尾部空白。 */public String trim() {}/** * 根据给定正则表达式的匹配拆分此字符串。 */public String[] split(String regex) {}
package solutions._151;public class Solution { public String reverseWords(String s) { s = s.trim(); String[] arrs = s.split("\\s+"); if (arrs.length == 0) { return ""; } StringBuilder sb = new StringBuilder(s.length()); for (int i = arrs.length - 1; i > 0; i--) { sb.append(arrs[i]); sb.append(" "); } sb.append(arrs[0]); return sb.toString(); } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.reverseWords("a b c d e f g")); }}
正则表达式\s
表示匹配任何空白字符,+
表示匹配一次或多次。
阅读全文
0 0
- LeetCode 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
- Leetcode-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
- Leetcode 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
- LeetCode - 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
- [LeetCode] 151. Reverse Words in a String
- Leetcode-151. Reverse Words in a String
- 第八周项目2
- Netlink实现Linux内核与用户空间通信
- Android 7.1.1 Launcher3 去除Quick Search Bar
- Windows 绿色安装PHP
- 第十一周项目2---操作用邻接表存储的图
- LeetCode-151. Reverse Words in a String
- 打包遇到的bugcom.android.ide.common.signing.KeytoolException: Failed to read key youzhi from store "C:\yo
- Gremlin简介
- Spring-Boot (一) Hello Wrold!
- H5播放视频控件介绍
- Flume整体汇总
- 二 Java基础语法
- STS 编辑器与Myeclipse工作空间冲突问题
- 我所理解的Android和iOS上的View