---
# System prepended metadata

title: 1592. Rearrange Spaces Between Words
tags: [Leetcode, Easy, String]

---

# 1592. Rearrange Spaces Between Words
###### tags: `Leetcode` `Easy` `String`
Link: https://leetcode.com/problems/rearrange-spaces-between-words/description/
## 思路
```text.split(" ")```只能split by一个空格
```text.split("\\s+")```才能去除单词间的连续空格
注意```String.join()```和```" ".repeat()```的用法
## Code
```java=
class Solution {
    public String reorderSpaces(String text) {
        String[] word = text.trim().split("\\s+");
        int cnt = 0;
        for(int i=0; i<text.length(); i++){
            if(text.charAt(i)==' ') cnt++;
        }
        int gap = word.length==1?0:cnt/(word.length-1);
        int trailingSpace = cnt-gap*(word.length-1);
        return String.join(" ".repeat(gap), word)+" ".repeat(trailingSpace);
    }
}
```