-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1324-PrintWordsVertically.go
More file actions
76 lines (68 loc) · 2.29 KB
/
1324-PrintWordsVertically.go
File metadata and controls
76 lines (68 loc) · 2.29 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
// 1324. Print Words Vertically
// Given a string s. Return all the words vertically in the same order in which they appear in s.
// Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
// Each word would be put on only one column and that in one column there will be only one word.
// Example 1:
// Input: s = "HOW ARE YOU"
// Output: ["HAY","ORO","WEU"]
// Explanation: Each word is printed vertically.
// "HAY"
// "ORO"
// "WEU"
// Example 2:
// Input: s = "TO BE OR NOT TO BE"
// Output: ["TBONTB","OEROOE"," T"]
// Explanation: Trailing spaces is not allowed.
// "TBONTB"
// "OEROOE"
// " T"
// Example 3:
// Input: s = "CONTEST IS COMING"
// Output: ["CIC","OSO","N M","T I","E N","S G","T"]
// Constraints:
// 1 <= s.length <= 200
// s contains only upper case English letters.
// It's guaranteed that there is only one space between 2 words.
import "fmt"
import "strings"
func printVertically(s string) []string {
if len(s)==0 { return []string{} }
rows := []string{}
for i, line := range strings.Split(s, " ") {
for j, c := range line {
// expand rows if there are more characters in the line
if j >= len(rows) {
rows = append(rows, "")
}
// add padding space if current row is shorter than the line number
if len(rows[j]) < i {
rows[j] += strings.Repeat(" ", i - len(rows[j]))
}
rows[j] += string(c)
}
}
return rows
}
func main() {
// Example 1:
// Input: s = "HOW ARE YOU"
// Output: ["HAY","ORO","WEU"]
// Explanation: Each word is printed vertically.
// "HAY"
// "ORO"
// "WEU"
fmt.Println(printVertically("HOW ARE YOU")) // ["HAY","ORO","WEU"]
// Example 2:
// Input: s = "TO BE OR NOT TO BE"
// Output: ["TBONTB","OEROOE"," T"]
// Explanation: Trailing spaces is not allowed.
// "TBONTB"
// "OEROOE"
// " T"
fmt.Println(printVertically("TO BE OR NOT TO BE")) // ["TBONTB","OEROOE"," T"]
// Example 3:
// Input: s = "CONTEST IS COMING"
// Output: ["CIC","OSO","N M","T I","E N","S G","T"]
fmt.Println(printVertically("CONTEST IS COMING")) // ["CIC","OSO","N M","T I","E N","S G","T"]
}