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.

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()方法,去除首尾空格

文章已创建 112


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