N

(Leet Code JS)Rearrange Spaces Between Words 본문

Leet Code 알고리즘

(Leet Code JS)Rearrange Spaces Between Words

naeunchan 2022. 2. 8. 09:59
728x90
반응형

https://leetcode.com/problems/rearrange-spaces-between-words/submissions/

 

Rearrange Spaces Between Words - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

/**
 * @param {string} text
 * @return {string}
 */
const reorderSpaces = (text) => {
    let space = 0;
    let string = "";
    const splitedText = [];
    
    for(let i = 0; i < text.length; i++){
        if(text[i] === " "){
            if(string.length){
                splitedText.push(string);
                string = "";
            }
            space++;
        } else{
            string += text[i];
        }
    }
    
    if(string.length){
        splitedText.push(string);
    }
    
    if(!space){
        return text;
    }
    
    const length = splitedText.length - 1 ? splitedText.length - 1 : 1;
    const q = Math.floor(space / length);
    const r = space % length;
    const sep = Array(q).fill(" ").join("");
    const ext = Array(r).fill(" ").join("");
    
    return splitedText.length === 1 ? splitedText[0] + sep : splitedText.join(sep) + (r ? ext : "");
};
728x90
반응형