[Swift]LeetCode68. 文本左右對齊 | Text Justification

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-dnukjxjx-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.git

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.github

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.算法

For the last line of text, it should be left justified and no extra space is inserted between words.數組

Note:微信

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Example 1:app

Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Example 2:ide

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:spa

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                  "
]

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

你應該使用「貪心算法」來放置給定的單詞;也就是說,儘量多地往每行中放置單詞。必要時可用空格 ' ' 填充,使得每行剛好有 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                  "
]

8ms
 1 class Solution {
 2     func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
 3         var res:[String] = [String]()
 4         var i:Int = 0
 5         while(i < words.count)
 6         {
 7             var j:Int = i
 8             var len:Int = 0
 9             while(j < words.count && (len+words[j].count + j - i ) <= maxWidth)
10             {
11                 len += words[j].count
12                 j += 1
13             }
14             var out:String = String()
15             var space:Int = maxWidth - len
16             for k in i..<j
17             {
18                 out += words[k]
19                 if space>0
20                 {
21                     var t:Int = 0
22                     if j == words.count
23                     {
24                         if j - k == 1
25                         {
26                             t = space
27                         }
28                         else
29                         {
30                             t = 1
31                         }
32                     }
33                     //no last row
34                     else
35                     {
36                         //last word
37                         if j - k - 1 > 0
38                         {
39                             if space % (j - k - 1) == 0
40                             {
41                                 t = space / (j - k - 1)
42                             }
43                             else
44                             {
45                                 t = space / (j - k - 1) + 1
46                             }
47                         }
48                         else
49                         {
50                             t = space
51                         }
52                     }
53                     space -= t
54                     out += String(repeating:" ",count:t)
55                 }
56             }
57             res.append(out)
58             i = j
59         }
60         return res
61     }
62 }

8ms

 1 class Solution {
 2     func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
 3         var result = [String]()
 4         
 5         var currentLine = [String]()
 6         var currentCount = 0
 7         var currentWordCount = 0
 8         
 9         for word in words {
10             
11             let wordCount = word.count
12             
13             if maxWidth - currentCount - currentWordCount >= wordCount {
14                 currentLine.append(word)
15                 currentCount += wordCount
16                 currentWordCount += 1
17             } else {
18                 let lineText = makeLine(currentLine, currentCount, currentWordCount, maxWidth)
19                 
20                 result.append(lineText)
21                 
22                 currentLine = [word]
23                 currentCount = wordCount
24                 currentWordCount = 1
25             }
26         }
27         
28         if currentWordCount > 0 {
29             result.append(makeLine([currentLine.joined(separator: " ")], currentCount + currentWordCount - 1, 1, maxWidth))
30         }
31         
32         return result
33     }
34     
35     private func makeLine(_ line: [String], _ currentCount: Int, _ currentWordCount: Int, _ maxWidth: Int) -> String {
36         
37         var currentLine = line
38         
39         let spaceNeeded = maxWidth - currentCount
40         
41         if currentWordCount == 1, let text = currentLine.first {
42             return text + String(repeating: " ", count: spaceNeeded)
43         }
44         
45         let spotOpen = currentLine.count - 1
46 
47         let spaceToAdd = spaceNeeded / spotOpen
48         var extraSpaceToAdd = spaceNeeded % spotOpen
49         
50         for i in 0..<extraSpaceToAdd {
51             currentLine[i] += " "
52         }
53         
54         return currentLine.joined(separator: String(repeating: " ", count: spaceToAdd))
55     }
56 }

12ms

 1 class Solution {
 2     var line: [String] = []
 3     
 4     func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
 5         var words = words
 6         var result = [String]()
 7 
 8         while !words.isEmpty {
 9             line = []
10 
11             while let w = words.first, w.count + length() + line.count <= maxWidth {
12                 line.append(words.removeFirst())
13             }
14 
15             var linestring = line.removeFirst()
16 
17            while !line.isEmpty {
18                 
19                let spacer = words.isEmpty ? 1 : (maxWidth - linestring.count - length() + line.count - 1) / line.count
20                linestring += String(repeating: " ", count: spacer) + line.removeFirst()
21             }
22             
23             linestring += String(repeating: " ", count: max(0, maxWidth - linestring.count))
24             result.append(linestring)
25         }
26         return result
27     }
28     
29     func length() -> Int {
30         return line.reduce(0) {$0 + $1.count}
31     }
32 }

 1 class Solution {
 2     func commitLine(_ words: [String], _ maxWidth: Int, _ isLastLine: Bool) -> String {
 3         var spaceCount = maxWidth
 4         for word in words {
 5             spaceCount -= word.count
 6         }
 7         
 8         var result = ""
 9         if words.count > 1 {
10             let avgSpaceCount = spaceCount / (words.count - 1)
11             let extSpaceCount = spaceCount % (words.count - 1)
12             for i in 0..<words.count - 1 {
13                 result = result + words[i] + String(repeating: " ", count: isLastLine ? 1 : (avgSpaceCount + (i < extSpaceCount ? 1 : 0)))
14             }
15             result += words.last!
16             if isLastLine && (maxWidth - result.count) > 0 {
17                 result += String(repeating: " ", count: maxWidth - result.count)
18             }
19         } else {
20             result = result + words.first! + String(repeating: " ", count: spaceCount)
21         }
22         
23         return result
24     }
25     
26     func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
27         var result = [String]()
28         var lineWords = [String]()
29         var lineSpace = maxWidth
30         for i in 0..<words.count {
31             if lineSpace <= 0 {
32                 result.append(commitLine(lineWords, maxWidth, false))
33                 lineWords = [String]()
34                 lineSpace = maxWidth
35             }
36             
37             if words[i].count <= lineSpace {
38                 lineWords.append(words[i])
39                 lineSpace = lineSpace - words[i].count - 1
40             } else {
41                 result.append(commitLine(lineWords, maxWidth, false))
42                 lineWords = [words[i]]
43                 lineSpace = maxWidth - words[i].count - 1
44             }
45         }
46         
47         result.append(commitLine(lineWords, maxWidth, true)) // Commit last line
48         return result
49     }
50 }
相關文章
相關標籤/搜索