This problem is not very hard to think, while we need to pay attentions to details and corner cases.
Solution:
# T:O(n) S:O(1) class Solution: # @param {string[]} words # @param {integer} maxWidth # @return {string[]} def fullJustify(self, words, maxWidth): L, N, wordLen, ret, i, j = maxWidth, len(words), [], [], 0, 0 for word in words: wordLen.append(len(word)) if not words: return [] while j < N: i = j + 1 total = wordLen[j] # total indicates len of words that can be put in this line while i < N and total + wordLen[i] < L: total += wordLen[i] + 1 # already insert 1 space between words i += 1 numOfExtraSpace = L - total numOfWords = i - j temp = words[j] if numOfWords == 1: ret.append(temp+' '*(L-wordLen[j])) j += 1 else: if i == N: while numOfWords > 1: temp += ' ' + words[j + 1] j += 1 numOfWords -= 1 ret.append(temp + ' '*numOfExtraSpace) return ret each = numOfExtraSpace/(numOfWords-1) left = numOfExtraSpace % (numOfWords-1) while numOfWords > 1: if left > 0: temp += ' '*(each+2) + words[j + 1] left -= 1 else: temp += ' '*(each+1) + words[j + 1] j += 1 numOfWords -= 1 ret.append(temp) j += 1 return retRun Time: 44 ms
No comments:
Post a Comment