250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code JS)Rearrange Spaces Between Words 본문
728x90
반응형
https://leetcode.com/problems/rearrange-spaces-between-words/submissions/
/**
* @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
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS)Min Cost Climbing Stairs (0) | 2022.02.17 |
---|---|
(Leet Code JS)Find And Replace in String (0) | 2022.02.08 |
(Leet Code JS)Path With Minimum Effort (0) | 2022.01.22 |
(Leet Code JS)Minimum Path Sum (0) | 2022.01.20 |
(Leet Code JS)Network Delay Time (0) | 2022.01.20 |