1. 程式人生 > >騰訊// 反轉字串中的單詞 III

騰訊// 反轉字串中的單詞 III

給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。

示例 1:

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

注意:在字串中,每個單詞由單個空格分隔,並且字串中不會有任何額外的空格。

先用split把各個單詞分割開來,然後把各個單詞翻轉在連線成一個字串,中間不要忘了加空格,最後一個不用加.

class Solution {
    public String reverseWords(String s) {
        String[] str = s.split(" ");
        String ns = "";
        for(int i = 0; i < str.length; i++){
            char[] c = new char[str[i].length()];
            for(int j = 0; j < str[i].length(); j++){
                c[j] = str[i].charAt(str[i].length()-j-1);
            }
            if(i!=str.length-1)
                ns+=String.valueOf(c)+" ";
            else
                ns+=String.valueOf(c);
        }
        return ns;
    }
}