leetcode557-反转字符串中的单词III

原题

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例1:

输入: “Let’s take LeetCode contest”
输出: “s’teL ekat edoCteeL tsetnoc”

注意: 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

解法

思想

翻转字符串可以用StringBuffer的reverse方法。

代码

class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for(String word:words){
            sb.append(new StringBuffer(word).reverse().toString());
            sb.append(" ");
        }
        return sb.toString().trim();

    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode557-%e5%8f%8d%e8%bd%ac%e5%ad%97%e7%ac%a6%e4%b8%b2%e4%b8%ad%e7%9a%84%e5%8d%95%e8%af%8diii/

发表回复

登录后才能评论