Press "Enter" to skip to content

Reverse Words in a String III-LeetCode#557

557. Reverse Words in a String III

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.

 思路:给定一个字符串,你需要颠倒句子中每个单词中的字符顺序,同时仍然保留空格和初始单词顺序。可以运用StringBuilder的reverse方法。
代码如下:
public class ReverseWordsInAStringIII {
    public static String reverseWords(String s) {
        String[] strings = s.split(" ");
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            StringBuilder temp = new StringBuilder(strings[i]);
            res.append(temp.reverse() + " ");
        }
        return res.toString().trim();
    }
}

p: String的trim()方法,去除首尾空格

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注