Rearrange Spaces Between Words

🏠 ⬅️ ➡️

You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.

Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.

Return the string after rearranging the spaces.

Example 1:

Input: text = " this is a sentence " Output: "this is a sentence " Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.

Example 2:

Input: text = " practice makes perfect " Output: "practice makes perfect " Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.

Constraints:

  • 1 <= text.length <= 100
  • text consists of lowercase English letters and ' '.
  • text contains at least one word.

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    character(len=:), allocatable :: text
    integer :: nwords, i

    call get_command_argument(1, text)

    nwords = count(text == ' ') + 1

    if (nwords > 1) then
        do i = 1, nwords - 1
            write (*,'(*(g0))') text(1:i-1), ' ', text(i+1:)
        end do
    else
        write (*,'(*(g0))') text
    end if

end program main
Compiled
Executed
Correct
module rearranging_spaces

implicit none

contains

function rearrange_spaces(text) result(result)

character(len=*), intent(in) :: text
character(len=len(text)) :: result

integer :: i, j, k, n, m

! Find the number of words and the number of spaces
n = count(text == ' ') + 1
m = count(text /= ' ')

! If there is only one word, return the original string
if (n == 1) then
    result = text
    return
end if

! Allocate memory for the result string
allocate(character(len=len(text)) :: result)

! Initialize the result string
result = ''

! Loop through the words and spaces
do i = 1, n
    ! Find the index of the next space
    do j = i, n
        if (text(j:j) == ' ') exit
    end do

    ! Copy the word to the result string
    result = result // text(i:j-1)

    ! If there are more spaces than words, add an extra space
    if (j < n) then
        result = result // ' '
    end if
end do

end function rearrange_spaces

end module

program test_rearranging_spaces

use rearranging_spaces, only : rearrange_spaces

implicit none

character(len=100) :: text
character(len=100) :: result

! Test case 1
text = "  this   is  a sentence  "
result = rearrange_spaces(text)
write (*,*) result

! Test case 2
text = " practice   makes   perfect "
result = rearrange_spaces(text)
write (*,*) result

! Test case 3
text = "hello world"
result = rearrange_spaces(text)
write (*,*) result

! Test case 4
text = "a"
result = rearrange_spaces(text)
write (*,*) result

! Test case 5
text = " "
result = rearrange_spaces(text)
write (*,*) result

end program
🌐 Data from online sources
def reorderSpaces(text):
    spaces = text.count(' ')
    words = text.split()
    num_words = len(words)

    if num_words == 1:
        spaces_between_words = 0
    else:
        spaces_between_words = spaces // (num_words - 1)

    extra_spaces = spaces - spaces_between_words * (num_words - 1)

    return (' ' * spaces_between_words).join(words) + ' ' * extra_spaces

To solve this problem, first we need to count the number of spaces and words in the input text. We iterate through the text and count the spaces. Then, we split the text into words, and count the number of words.

Next, we need to calculate the number of spaces between words and the extra spaces that will be placed at the end. If there is only one word, then all spaces will be used as extra spaces. Otherwise, we divide the total number of spaces by the number of words minus 1 (to get the spaces between words), and calculate the remainder (i.e., the extra spaces).

After that, we construct the result by joining the words with the calculated space between them and then adding the extra spaces at the end of the last word.

In all four implementations, the core logic and step-by-step procedure are the same, only the syntax and library functions vary according to the language being used.

🌐 Data from online sources
#include <string>
#include <vector>
#include <sstream>

std::string reorderSpaces(std::string text) {
    int spaces = 0, words = 0;

    for (char c : text) {
        if (c == ' ') spaces++;
    }

    std::istringstream iss(text);
    std::vector<std::string> wordList;
    std::string word;

    while (iss >> word) {
        wordList.push_back(word);
        words++;
    }

    int spacesBetweenWords = words == 1 ? 0 : spaces / (words - 1);
    int extraSpaces = words == 1 ? spaces : spaces % (words - 1);

    std::string result;

    for (int i = 0; i < words; i++) {
        result += wordList[i];
        if (i != words - 1) {
            result.append(spacesBetweenWords, ' ');
        } else {
            result.append(extraSpaces, ' ');
        }
    }

    return result;
}

To solve this problem, first we need to count the number of spaces and words in the input text. We iterate through the text and count the spaces. Then, we split the text into words, and count the number of words.

Next, we need to calculate the number of spaces between words and the extra spaces that will be placed at the end. If there is only one word, then all spaces will be used as extra spaces. Otherwise, we divide the total number of spaces by the number of words minus 1 (to get the spaces between words), and calculate the remainder (i.e., the extra spaces).

After that, we construct the result by joining the words with the calculated space between them and then adding the extra spaces at the end of the last word.

In all four implementations, the core logic and step-by-step procedure are the same, only the syntax and library functions vary according to the language being used.