1. 程式人生 > >【一次過】Lintcode 1173. Reverse Words in a String III

【一次過】Lintcode 1173. 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.

樣例

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

注意事項

In the string, each word is separated by single space and there will not be any extra space in the string.

解題思路:

先用空格對字串進行分割,然後對每個字元進行翻轉,注意翻轉方法reverse()只有StringBuilder與StringBuffer才有。而trim()方法只有String才有,不要記混了。

public class Solution {
    /**
     * @param s: a string
     * @return: reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order
     */
    public String reverseWords(String s) {
        // Write your code here
        String[] strs = s.split(" ");
        
        StringBuilder res = new StringBuilder();
        
        for(String str : strs){
            res.append(new StringBuilder(str).reverse());
            res.append(" ");
        }
        
        return res.toString().trim();
    }
}