HDU 2115 I Love This Game(结构体排序 or pair)
902
2022-08-22
[leetcode] 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.
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 <= 100text consists of lowercase English letters and ’ '.text contains at least one word.
分析
题目的意思是:重新排列字符串里面的空格。这道题如果用C++操作的话,估计写得有点难受,但是用python的话,就很容易,因为python对字符串切分,拼接非常友好,哈哈哈。
代码
class Solution: def reorderSpaces(self, text: str) -> str: space=text.count(' ') words=text.strip().split() n=len(words) if(n==1): return ''.join(words)+' '*space q=space//(n-1) r=space%(n-1) return (' '*q).join(words)+' '*r
参考文献
[LeetCode] Python3 simple solution - Rearrange Spaces Between Words
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。