原题地址:https://oj.leetcode.com/problems/text-justification/
题目大致意思是:给定一个字符串数组,和一个整数L,把这个字符串按一定形式输出。
题目比较简单,也没什么特别的算法。直接给出代码。
class Solution:
# @param words, a list of strings
# @param L, an integer
# @return a list of strings
def fullJustify(self, words, L):
if L==0:
return [""]
lines = []
start,count = 0,0
line = ""
for i in range(0,len(words)):
if (count + (len(words[i])+1))<=L+1:
count += len(words[i])+1
else:
space = L-(count-i+start)
for j in range(start,i):
if space == 0 or i-start==1:
line += words[j] + space*" "
elif space == space//(i-1-j)*(i-1-j):
line += words[j] + space/(i-1-j)*" "
space -= space/(i-1-j)
else:
line += words[j] + (space//(i-1-j)+1)*" "
space -= space//(i-1-j)+1
lines.append(line)
start = i
line = ""
count = len(words[i])+1
if count != 0:
line = " ".join(words[start::])
lines.append( line + (L-len(line))*" ")
print lines
Solution().fullJustify([""], 2)