您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“C++如何實現文本左右對齊”,內容詳細,步驟清晰,細節處理妥當,希望這篇“C++如何實現文本左右對齊”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
Example 1:
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]
Example 2:
Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
"What must be",
"acknowledgment ",
"shall be "
]
Explanation: Note that the last line is "shall be " instead of "shall be",
because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified becase it contains only one word.
Example 3:
Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
"to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]
我將這道題翻譯為文本的左右對齊是因為這道題像極了word軟件里面的文本左右對齊功能,這道題我前前后后折騰了快四個小時終于通過了OJ,完成了之后想著去網上搜搜看有沒有更簡單的方法,搜了一圈發現都差不多,都挺復雜的,于是乎就按自己的思路來說吧,由于返回的結果是多行的,所以我們在處理的時候也要一行一行的來處理,首先要做的就是確定每一行能放下的單詞數,這個不難,就是比較n個單詞的長度和加上n - 1個空格的長度跟給定的長度L來比較即可,找到了一行能放下的單詞個數,然后計算出這一行存在的空格的個數,是用給定的長度L減去這一行所有單詞的長度和。得到了空格的個數之后,就要在每個單詞后面插入這些空格,這里有兩種情況,比如某一行有兩個單詞"to" 和 "a",給定長度L為6,如果這行不是最后一行,那么應該輸出"to a",如果是最后一行,則應該輸出 "to a ",所以這里需要分情況討論,最后一行的處理方法和其他行之間略有不同。最后一個難點就是,如果一行有三個單詞,這時候中間有兩個空,如果空格數不是2的倍數,那么左邊的空間里要比右邊的空間里多加入一個空格,那么我們只需要用總的空格數除以空間個數,能除盡最好,說明能平均分配,除不盡的話就多加個空格放在左邊的空間里,以此類推,具體實現過程還是看代碼吧:
class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { vector<string> res; int i = 0; while (i < words.size()) { int j = i, len = 0; while (j < words.size() && len + words[j].size() + j - i <= L) { len += words[j++].size(); } string out; int space = L - len; for (int k = i; k < j; ++k) { out += words[k]; if (space > 0) { int tmp; if (j == words.size()) { if (j - k == 1) tmp = space; else tmp = 1; } else { if (j - k - 1 > 0) { if (space % (j - k - 1) == 0) tmp = space / (j - k - 1); else tmp = space / (j - k - 1) + 1; } else tmp = space; } out.append(tmp, " "); space -= tmp; } } res.push_back(out); i = j; } return res; } };
讀到這里,這篇“C++如何實現文本左右對齊”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。