Leetcod:557.Reverse Words in a String III 反转字符串中的每个单词。

来源:互联网 发布:淘宝开专卖店 编辑:程序博客网 时间:2024/05/16 19:11

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:
Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
Note: In the string, each word is separated by single space and there will not be any extra space in the string.

    /**     * 把一个字符串中的每个单词反向输出!     * 思路:     * 1.先把一个字符串转换成字符串数组、     * 2.每一个单词利用StringBuffer的方法进行Reverse操作     * 3.再合并操作     * 4.裁剪字符串的首位的空格     * @param s     * @return     */    public static String reverseWords(String s) {        String[] revSplit = s.split(" ");        String revString = "";        for (int i = 0; i < revSplit.length; i++) {            revSplit[i] = new StringBuffer(revSplit[i]).reverse().toString();            revString = revString +" " +revSplit[i];        }        return revString.trim();    }

但是感觉这样执行效率不怎么高。
Just Beats 9.02%!

阅读全文
0 0
原创粉丝点击