Markdown

557. Reverse Words in a String III

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.

/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    var arr1 = [];
    var ans = [];
    var ans2 = ""
    
    //reverse arr1
    arr1 = s.split(" ");
    for (let i = 0 ;i<arr1.length;i++){
        var arr3 = "";
        arr3 = arr1[i].toString();
        arr3 = arr3.split("").reverse().join("");

        ans.push(arr3);
    }
    
    var add = ans.pop();
    
    for(let i=0; i<ans.length; i++){
        ans2 += ans[i]+" ";
    }
    return(ans2+add);
    // if there are any "," in string ,then they would be replace so do not use replace
    //return(ans.toString().replace(/,/g," "))
};

想法:
1.先將字串拆成陣列
2.將每個元素拆成字串反轉完裝回去 得到新陣列
3.將最後一個元素去掉
4.將陣列中剩餘的元素插入空格組合成字串
5.再將去掉的元素加進來

錯誤嘗試:
一開始因為直接把步驟2直接toString導致中間會多出許多逗號
第一反應是去掉逗號 然後用空白取代 多方便R
但沒考慮到測資中可能有逗號XD 掛在最後一次



觀摩區:

Approach #1 Simple Solution[Accepted]

The first method is really simple. We simply split up the given string based on whitespaces and put the individual words in an array of strings. Then, we reverse each individual string and concatenate the result. We return the result after removing the additional whitespaces at the end.
Java
public class Solution {
    public String reverseWords(String s) {
        String words[] = s.split(" ");
        String res = "";
        for (String word: words)
            res += new StringBuffer(word).reverse().toString() + " ";
        return res.trim();
    }
}
Complexity Analysis
  • Time complexity : O(n). where n is the length of the string.
  • Space complexity : O(n)res of size n is used.

    String 類別 (class) 有 trim() 方法 (method) ,回傳去除首尾空白符號的子字串






https://discuss.leetcode.com/topic/86271/javascript-129ms-any-suggestion-is-welcome  


留言