标签:pre 左右 maxwidth size 条件 文本 word color join
一维转二维再转一维
思路:
先根据最大长度条件把一维数组转换为二维数组,二维数组中的每个数组是结果中每个字符串包含的所有单词。再对二维数组中每个数组进行加空格处理,这里要注意的是,要对最后一行单独处理。
代码:
class Solution: def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: res = [] temp = [] path = [] curWidth = 0 for word in words: curwlen = len(word) if curWidth + curwlen +len(path) <= maxWidth: curWidth += curwlen path.append(word) else: temp.append(path[:]) path.clear() curWidth = curwlen path.append(word) for wds in temp: wStr = self.jointWordToStr(wds,maxWidth) res.append(wStr) lastStr = path[0] for i in range(1,len(path)): lastStr = lastStr + ‘ ‘ + path[i] lastStr = lastStr + ‘ ‘*(maxWidth-len(‘‘.join(path))-len(path)+1) res.append(lastStr) return res def jointWordToStr(self,words,maxWidth): listlen = len(words) if listlen == 1: return words[0]+ ‘ ‘*(maxWidth-len(words[0])) allAlp = 0 for i in range(listlen): allAlp += len(words[i]) avespace = (maxWidth - allAlp)//(listlen-1) exspace = (maxWidth - allAlp)-avespace*(listlen-1) wStr = words[0] for i in range(exspace): wStr = wStr + ‘ ‘*(avespace+1)+words[i+1] for i in range(exspace,listlen-1): wStr = wStr + ‘ ‘*avespace + words[i+1] return wStr
标签:pre 左右 maxwidth size 条件 文本 word color join
原文地址:https://www.cnblogs.com/nilhxzcode/p/13081355.html