 # [刷题记录板] [leetcode] （Dec,17）每天两道题目，配 python参考解答

20主题 586积分 586 发表于 12-17-2014 01:56 PM | 显示全部楼层 |阅读模式

### 亲！马上注册或者登录会查看更多内容！

x

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as:
[
"This    is    an",
"example  of text",
"justification.  "
]
Note: Each word is guaranteed not to exceed L in length.

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].  python参考解答：

[code]class Solution:
# @param words, a list of strings
# @param L, an integer
# @return a list of strings
def fullJustify(self, words, L):
res=[]
i=0
while i             size=0; begin=i
while i                 newsize=len(words【i】) if size==0 else size+len(words【i】)+1
if newsize<=L: size=newsize
else: break
i+=1
spaceCount=L-size
if i-begin-1>0 and i                 everyCount=spaceCount/(i-begin-1)
spaceCount%=i-begin-1
else:
everyCount=0
j=begin
while j                 if j==begin: s=words[j]
else:
s+=' '*(everyCount+1)
if spaceCount>0 and i                         s+=' '
spaceCount-=1
s+=words[j]
j+=1
s+=' '*spaceCount
res.append(s)
return res[/code]

[code]# Definition for an interval.
# class Interval:
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution:
# @param intervals, a list of Intervals
# @param newInterval, a Interval
# @return a list of Interval
# @should rewrite without sort!!!
def insert(self, intervals, newInterval):
intervals.append(newInterval)
intervals.sort(key = lambda x:x.start)
length=len(intervals)
res=[]
for i in range(length):
if res==[]:
res.append(intervals【i】)
else:
size=len(res)
if res[size-1].start<=intervals【i】.start<=res[size-1].end:
res[size-1].end=max(intervals【i】.end, res[size-1].end)
else:
res.append(intervals【i】)
return res[/code]

### 本帖被以下淘专辑推荐:

 本版积分规则 回帖后跳转到最后一页   