输入: words = ["This", "is", "an", "example", "of", "text", "justification."] maxWidth = 16 输出: [ "This is an", "example of text", "justification. " ]
示例 2:
1 2 3 4 5 6 7 8 9 10 11 12
输入: words = ["What","must","be","acknowledgment","shall","be"] maxWidth = 16 输出: [ "What must be", "acknowledgment ", "shall be " ] 解释: 注意最后一行的格式应为 "shall be " 而不是 "shall be", 因为最后一行应为左对齐,而不是左右两端对齐。 第二行同样为左对齐,这是因为这行只包含一个单词。
示例 3:
1 2 3 4 5 6 7 8 9 10 11 12 13
输入: words = ["Science","is","what","we","understand","well","enough","to","explain", "to","a","computer.","Art","is","everything","else","we","do"] maxWidth = 20 输出: [ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ]
解答:
思路:
这道题确实难。
解答和思考过程参考题解部分。
思路: 首先要理顺题意,给定一堆单词,让你放在固定长度字符串里
两个单词之间至少有一个空格,如果单词加空格长度超过maxWidth,说明该单词放不下,比如示例1:当我们保证this is an 再加入example变成this is an example总长度超过maxWidth,所以这一行只能放下this is an 这三个单词;
this is an长度小于maxWidth,我们考虑分配空格,并保证左边空格数大于右边的
最后一行,要尽量靠左,例如示例2的:”shall be “
我们针对上面三个问题,有如下解决方案.
先找到一行最多可以容下几个单词;
分配空格,例如this is an ,对于宽度为maxWidth,我们可以用maxWidth - all_word_len 与需要空格数商为 单词间 空格至少的个数,余数是一个一个分配给左边.就能保证左边空格数大于右边的.例如 16 - 8 = 8 ,a = 8 / 2, b = 8 % 2两个单词间要有4个空格,因为余数为零不用分配;
classSolution(object): deffullJustify(self, words, maxWidth): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ res = [] n = len(words) i = 0 defone_row_words(i): left = i cur_row = len(words[i]) i += 1 while i < n: if cur_row + len(words[i]) + 1 > maxWidth: break cur_row += len(words[i]) + 1 i += 1 return left,i while i < n: left,i = one_row_words(i) one_row = words[left:i] if i == n: res.append(' '.join(one_row).ljust(maxWidth,' ')) break all_word_len = sum(len(i) for i in one_row) space_num = i - left - 1 remain_space = maxWidth - all_word_len if space_num: a,b = divmod(remain_space,space_num) tmp = '' for word in one_row: if tmp: tmp += ' '*a if b: tmp += ' ' b -= 1 tmp += word res.append(tmp.ljust(maxWidth,' ')) return res
classSolution(object): defmySqrt(self, x): """ :type x: int :rtype: int """ if x == 0: return0 if x == 1: return1 l ,r = 0,x-1 while l <= r: mid = l +((r-l)>>1) if mid * mid <= x and (mid+1) * (mid +1) > x: return mid elif mid * mid <x: l = mid + 1 else: r = mid - 1
思路二:牛顿法
1 2 3 4 5 6 7 8 9 10
classSolution(object): defmySqrt(self, x): """ :type x: int :rtype: int """ t = x while t * t >x: t = (t + x/t)/2 return t
classSolution(object): defclimbStairs(self, n): """ :type n: int :rtype: int """ a = 1 b = 2 if n == 1: return1 if n == 2: return2 for i inrange(2,n): a,b = b,a+b return b