Skip to content

Commit 21ac821

Browse files
committed
Add solution #1592
1 parent 1d715a6 commit 21ac821

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,404 LeetCode solutions in JavaScript
1+
# 1,405 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1229,6 +1229,7 @@
12291229
1589|[Maximum Sum Obtained of Any Permutation](./solutions/1589-maximum-sum-obtained-of-any-permutation.js)|Medium|
12301230
1590|[Make Sum Divisible by P](./solutions/1590-make-sum-divisible-by-p.js)|Medium|
12311231
1591|[Strange Printer II](./solutions/1591-strange-printer-ii.js)|Hard|
1232+
1592|[Rearrange Spaces Between Words](./solutions/1592-rearrange-spaces-between-words.js)|Easy|
12321233
1598|[Crawler Log Folder](./solutions/1598-crawler-log-folder.js)|Easy|
12331234
1657|[Determine if Two Strings Are Close](./solutions/1657-determine-if-two-strings-are-close.js)|Medium|
12341235
1668|[Maximum Repeating Substring](./solutions/1668-maximum-repeating-substring.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 1592. Rearrange Spaces Between Words
3+
* https://leetcode.com/problems/rearrange-spaces-between-words/
4+
* Difficulty: Easy
5+
*
6+
* You are given a string text of words that are placed among some number of spaces. Each word
7+
* consists of one or more lowercase English letters and are separated by at least one space.
8+
* It's guaranteed that text contains at least one word.
9+
*
10+
* Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent
11+
* words and that number is maximized. If you cannot redistribute all the spaces equally, place
12+
* the extra spaces at the end, meaning the returned string should be the same length as text.
13+
*
14+
* Return the string after rearranging the spaces.
15+
*/
16+
17+
/**
18+
* @param {string} text
19+
* @return {string}
20+
*/
21+
var reorderSpaces = function(text) {
22+
const words = text.trim().split(/\s+/);
23+
const spaceCount = text.length - words.join('').length;
24+
const wordCount = words.length;
25+
26+
if (wordCount === 1) return words[0] + ' '.repeat(spaceCount);
27+
28+
const spacesBetween = Math.floor(spaceCount / (wordCount - 1));
29+
const extraSpaces = spaceCount % (wordCount - 1);
30+
31+
return words.join(' '.repeat(spacesBetween)) + ' '.repeat(extraSpaces);
32+
};

0 commit comments

Comments
 (0)