鱼C论坛

 找回密码
 立即注册
查看: 2018|回复: 0

[学习笔记] Leetcode 1592. Rearrange Spaces Between Words

[复制链接]
发表于 2020-9-21 08:04:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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.
Example 3:

Input: text = "hello   world"
Output: "hello   world"
Example 4:

Input: text = "  walks  udp package   into  bar a"
Output: "walks  udp  package  into  bar  a "
Example 5:

Input: text = "a"
Output: "a"


Constraints:

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

  1. class Solution:
  2.     def reorderSpaces(self, text: str) -> str:
  3.         whitespace = 0
  4.         words = text.strip().split()
  5.         
  6.         numOfWords = len(words)
  7.         
  8.         for c in text:
  9.             if c == ' ':
  10.                 whitespace += 1
  11.         
  12.         if len(words) == 1:
  13.             return words[0] + ' ' * whitespace
  14.         
  15.         space = whitespace // (numOfWords - 1)
  16.         remain = whitespace - space * (numOfWords - 1)
  17.         result = ''
  18.         # print(text, whitespace, numOfWords, space)
  19.         
  20.         for i in range(len(words) - 1):
  21.             result += words[i] + ' ' * space
  22.         
  23.         result += words[len(words) - 1] + ' ' * remain
  24.         return result
  25.             
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-23 16:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表