leetcode【每日一题】557. 反转字符串中的单词 III Java

题干

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

示例:

输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"

提示:

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

想法

转成数组
再对每一个反转
再拼接 去空即可

Java代码

class Solution {
   public String reverseWords(String s) {

        if (s.length() == 0 || s == null) {
            return "";
        }
        if (s == " ") {
            return "";
        }
        StringBuffer stringBuffer = new StringBuffer();
        String[] strings = s.split(" ");
        for (String tem : strings
        ) {
            StringBuffer stringBuffer1 = new StringBuffer(tem);
            stringBuffer1.reverse();
            String str = stringBuffer1.toString();
            stringBuffer.append((str));
            stringBuffer.append(" ");

        }
        String s1 = stringBuffer.toString().trim();
        return s1;
    }

}

我的leetcode代码都已经上传到我的githttps://github.com/ragezor/leetcode

猜你喜欢

转载自blog.csdn.net/qq_43491066/article/details/108307367
今日推荐