用 Python 编写一个重新排列单词间空格的程序

pythonserver side programmingprogramming更新于 2025/5/1 0:44:17

假设我们有一个字符串 s,其中有一些单词位于一定数量的空格之间。每个单词之间至少有一个空格。我们必须重新排列空格,使每对相邻单词之间的空格数相同,并且每个单词之间的空格数最大化。如果我们无法平等地重新分配所有空格,我们可以将多余的空格放在末尾。

因此,如果输入类似 s = "我爱编程",那么输出将是"我爱编程",看到空格分布,单词之间有五个空格。

为了解决这个问题,我们将按照以下步骤 −

  • res := 空字符串

  • total_sp := s 中的空格数

  • suff_sp_cnt := total_sp

  • text_array := 来自 s 的单词列表

  • num_words := text_array 的大小

  • 如果 num_words 等于 1,则

    • res := text_array[0] 与 total_sp 数量连接空格

    • 返回 res

  • sep_size := total_sp /(num_words - 1) 的商

  • sep := sep_size 空格数

  • 对于 text_array 中的每个 i - 1,执行

    • res := res + i

    • res := res + sep

    • suff_sp_cnt := suff_sp_cnt - sep_size

  • suff_sp_cnt := suff_sp_cnt + sep_size

  • res := 删除左侧和右侧的额外空格

  • res := res 在末尾连接 suff_sp_cnt 个空格

  • 返回 res

示例 (Python)

让我们看看下面的实现以便更好地理解 −

def solve(s):
   res = ""
   total_sp = s.count(" ")
   suff_sp_cnt = total_sp

   text_array = s.split()
   num_words = len(text_array)

   if num_words == 1:
      res = text_array[0] + total_sp * " "
      return res

   sep_size = total_sp // (num_words - 1)
   sep = sep_size * " "

   for i in text_array:
      res += i
      res += sep
      suff_sp_cnt -= sep_size

   suff_sp_cnt += sep_size
   res = res.strip()
   res += suff_sp_cnt * " "

   return res

s = " I love programming "
print(solve(s))

输入

" I love programming "

输出

"I love programming "

相关文章


有用资源