'LeetCode算法第68題:文本左右對齊'

算法 鏡音雙子 Java 小天使淘淘 2019-08-05
"

問題描述:

給定一個單詞數組和一個長度 maxWidth,重新排版單詞,使其成為每行恰好有 maxWidth 個字符,且左右兩端對齊的文本。

你應該使用“貪心算法”來放置給定的單詞;也就是說,儘可能多地往每行中放置單詞。必要時可用空格 ' ' 填充,使得每行恰好有 maxWidth 個字符。

要求儘可能均勻分配單詞間的空格數量。如果某一行單詞間的空格不能均勻分配,則左側放置的空格數要多於右側的空格數。

文本的最後一行應為左對齊,且單詞之間不插入額外的空格。

說明:

單詞是指由非空格字符組成的字符序列。

每個單詞的長度大於 0,小於等於 maxWidth。

輸入單詞數組 words 至少包含一個單詞。

示例:

輸入:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
輸出:
[
"This is an",
"example of text",
"justification. "
]

示例 2:

輸入:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
輸出:
[
"What must be",
"acknowledgment ",
"shall be "
]
解釋: 注意最後一行的格式應為 "shall be " 而不是 "shall be",
因為最後一行應為左對齊,而不是左右兩端對齊。
第二行同樣為左對齊,這是因為這行只包含一個單詞。

示例 3:

輸入:
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限制,則使用空格來進行填充。填充過程中使用(space / (end - start - 1))來計算平均兩個字符串之間填充幾個空格,使用(space % (end - start - 1)) 來計算前面有幾個字符串之間需要多添加一個空格。

java代碼:

public List<String> fullJustify(String[] words, int maxWidth) {
List<String> result = new ArrayList();
int curLen = 0;
int start = 0;
int end = 0;
for(int i = 0; i < words.length; ){
String str = words[i];
int len = str.length();
if(curLen == 0 && curLen + len <= maxWidth
|| curLen > 0 && curLen + 1 + len <= maxWidth){
end ++;
if(curLen == 0){
curLen += len;
}else{
curLen += 1 + len;
}
i ++;
}else{
int space = maxWidth - curLen + (end - start - 1);
if (end - start == 1) {
String blank = getStringBlank(space);
result.add(words[start] + blank);
} else {
StringBuilder temp = new StringBuilder();
temp.append(words[start]);
int averageBlank = space / (end - start - 1);
int mod = space % (end - start - 1);
String blank = getStringBlank(averageBlank + 1);
int k = 1;
for (int j = 0; j < mod; j++) {
temp.append(blank + words[start+k]);
k++;
}
blank = getStringBlank(averageBlank);
for (; k <(end - start); k++) {
temp.append(blank + words[start+k]);
}
result.add(temp.toString());
}
start = end;
curLen = 0;
}
}
StringBuilder temp = new StringBuilder();
temp.append(words[start]);
for (int i = 1; i < (end - start); i++) {
temp.append(" " + words[start+i]);
}
temp.append(getStringBlank(maxWidth - curLen));
result.add(temp.toString());
return result;
}

private String getStringBlank(int n) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < n; i++) {
str.append(" ");
}
return str.toString();
}
"

相關推薦

推薦中...