Problem

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.

Solution

class Solution {
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) return s;
        String[] strs = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (String str: strs) {
            str = reverse(str);
            sb.append(str).append(" ");
        }
        return sb.toString().trim();
    }
    private String reverse(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = str.length()-1; i >= 0; i--) {
            sb.append(str.charAt(i));
        }
        return sb.toString();
    }
}

StringBuilder for everything

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

linspiration
161 声望53 粉丝