2022/12/24

LeetCode 1859. Sorting the Sentence

問題:通過索引將文字組合成句子 解法:先切割字串,透過正規找出索引,根據索引加回陣列輸出即可 JavaScript
/**
 * @param {string} s
 * @return {string}
 */
var sortSentence = function (s) {
    let splitArray = s.split(" ");
    const reg = /\d+$/;

    let result = [];
    for (let i = 0; i < splitArray.length; i++) {
        const num = reg.exec(splitArray[i])[0];
        result[parseInt(num - 1)] = splitArray[i].replace(num, "");
    }

    return result.join(" ");
};