返回介绍

solution / 1500-1599 / 1592.Rearrange Spaces Between Words / README_EN

发布于 2024-06-17 01:03:16 字数 4593 浏览 0 评论 0 收藏 0

1592. Rearrange Spaces Between Words

中文文档

Description

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.

Solutions

Solution 1

class Solution:
  def reorderSpaces(self, text: str) -> str:
    cnt = text.count(' ')
    words = text.split()
    m = len(words) - 1
    if m == 0:
      return words[0] + ' ' * cnt
    return (' ' * (cnt // m)).join(words) + ' ' * (cnt % m)
class Solution {
  public String reorderSpaces(String text) {
    int cnt = 0;
    for (char c : text.toCharArray()) {
      if (c == ' ') {
        ++cnt;
      }
    }
    String[] words = text.split("\\s+");
    List<String> res = new ArrayList<>();
    for (String w : words) {
      if (!"".equals(w)) {
        res.add(w);
      }
    }
    int m = res.size() - 1;
    if (m == 0) {
      return res.get(0) + " ".repeat(cnt);
    }
    String ans = String.join(" ".repeat(cnt / m), res);
    ans += " ".repeat(cnt % m);
    return ans;
  }
}
func reorderSpaces(text string) string {
  cnt := strings.Count(text, " ")
  words := strings.Fields(text)
  m := len(words) - 1
  if m == 0 {
    return words[0] + strings.Repeat(" ", cnt)
  }
  return strings.Join(words, strings.Repeat(" ", cnt/m)) + strings.Repeat(" ", cnt%m)
}
function reorderSpaces(text: string): string {
  let count = 0;
  for (const c of text) {
    if (c === ' ') {
      count++;
    }
  }

  const words = text.trim().split(/\s+/g);
  const n = words.length;
  if (n === 1) {
    return words.join('') + ''.padStart(count);
  }

  const rest = count % (words.length - 1);
  const per = (count - rest) / (words.length - 1);
  return words.join(''.padStart(per)) + ''.padStart(rest);
}
impl Solution {
  fn create_spaces(n: usize) -> String {
    let mut res = String::new();
    for _ in 0..n {
      res.push(' ');
    }
    res
  }

  pub fn reorder_spaces(text: String) -> String {
    let count = {
      let mut res = 0;
      for c in text.as_bytes() {
        if c == &b' ' {
          res += 1;
        }
      }
      res
    };

    let works = text.split_whitespace().collect::<Vec<&str>>();
    let n = works.len();
    if n == 1 {
      return works[0].to_string() + &Self::create_spaces(count);
    }
    works.join(&Self::create_spaces(count / (n - 1))) + &Self::create_spaces(count % (n - 1))
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文