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表示匹配任何空白字符,+表示匹配一次或多次。