给一段句子,每个单词间空格有1*个,要求重排列让每个单词之间space数相同,且尽可能多。多余的放在尾巴上。
基本edge case都被题目排除了,没有什么难点。唯一留下的edge case 是只有一个单词的case
这道题把python比c++的字符串处理优势发挥的很好。 count split join 都是c++的痛
class Solution(object):
def reorderSpaces(self, text):
"""
:type text: str
:rtype: str
"""
cnt = text.count(' ')
words = [w for w in text.split() if len(w)!=0]
if (len(words)==1): # edge case
return words[0]+' '*cnt
d = cnt//(len(words)-1)
left = cnt-d*(len(words)-1)
return (' '*d).join(words)+' '*left
感觉csdn写lc查找不如evernote方便,还是改在en上写吧= =||| 这里留着读书源码工程笔记用