• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Swift]LeetCode68.文本左右对齐|TextJustification

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9923814.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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.

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.

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:

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

给定一个单词数组和一个长度 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                  "
]

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 }

19636 kb

 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 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
【Swift学习】Swift编程之旅---可选链(二十一)发布时间:2022-07-13
下一篇:
swift -- 计步器CMPedometer的使用发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap