Original question link: http://oj.leetcode.com/problems/text-justification/
This is a pure string operation. You need to arrange a string of words into strings with multiple lines of limited length. The main difficulty lies in the arrangement of spaces. First, each word must be separated by spaces. When Dangdang cannot put more words and the characters cannot fill the length of L, we need to fill the space evenly between words. If the remaining space is just a multiple of the intervals, the space can be evenly allocated. Otherwise, you must place an extra space in the preceding interval. In implementation, we maintain the current length of a count record. When the length exceeds, we calculate the common space and the additional space, and then construct the line string. The last detail is that there is no need to evenly allocate spaces for the last line. Leave the end of the sentence blank, so you have to handle it separately. In terms of time, we need to scan the word again, and then scan the word in the current row at the end of the row. However, each word is not accessed more than twice, therefore, the overall time complexity is O (n ). The spatial complexity is the size of the result (the number of Documentary Words is related to the length and cannot be accurately defined. If the number of last row r is known, it is O (r * L )). The Code is as follows:
Public ArrayList
FullJustify (String [] words, int L) {ArrayList
Res = new ArrayList
(); If (words = null | words. length = 0) return res; int count = 0; int last = 0; for (int I = 0; I
L) {int spaceNum = 0; int extraNum = 0; if (i-last-1> 0) {spaceNum = (L-count)/(i-last-1); extraNum = (L-count) % (i-last-1);} StringBuilder str = new StringBuilder (); for (int j = last; j
0) {str. append ("") ;}extranum -- ;}} for (int j = str. length (); j
This question belongs to the type of sub-operations for text editing. There is nothing special about the algorithm idea, but there are still a lot of implementation details, and it is not easy to do it right at a time, it may take several more exercises.