-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0068.Text Justification.swift
59 lines (45 loc) · 1.51 KB
/
0068.Text Justification.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
var res = [String]()
var idx = 0
while idx < words.count {
var width = words[idx].count
var pointer = idx + 1
while pointer < words.count {
if words[pointer].count + width + 1 > maxWidth {
break
}
width += words[pointer].count + 1
pointer += 1
}
var subRes = [String]()
let diff = pointer - idx - 1
if pointer == words.count || diff == 0 {
for i in idx..<pointer {
subRes.append(words[i])
subRes.append(" ")
}
subRes.removeLast()
var str = subRes.reduce("", +)
for i in str.count..<maxWidth {
str += " "
}
subRes = [str]
} else {
let spaces = (maxWidth - width) / diff
let r = (maxWidth - width) % diff
for i in idx..<pointer {
subRes.append(words[i])
if i < pointer - 1 {
for j in 0...(spaces + (i - idx < r ? 1 : 0)) {
subRes.append(" ")
}
}
}
}
res.append(subRes.reduce("", +))
idx = pointer
}
return res
}
}