Skip to content

Commit 1a30737

Browse files
committed
🎉 feat: initial commit for leetcode 94/96/98/804/832
1 parent f88abf8 commit 1a30737

5 files changed

+63
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// 804. Unique Morse Code Words
2+
// 20 ms
3+
let morseCode = ["a": "01", "b": "1000", "c": "1010", "d": "100", "e": "0", "f": "0010", "g": "110", "h": "0000", "i": "00", "j": "0111", "k": "101", "l": "0100", "m": "11", "n": "10", "o": "111", "p": "0110", "q": "1101", "r": "010", "s": "000", "t": "1", "u": "001", "v": "0001", "w": "011", "x": "1001", "y": "1011", "z": "1100"]
4+
return Set(
5+
words.map { w in
6+
w.reduce("") { s, c in
7+
s + morseCode[String(c)]!
8+
}
9+
}).count

Swift/832. Flipping an Image.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
// 832. Flipping an Image
2+
// 16 ms
3+
return A.map({$0.map({1-$0}).reversed()})
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// 94. Binary Tree Inorder Traversal
2+
// 8 ms, 100%
3+
4+
func inorderTraversal(_ root: TreeNode?) -> [Int] {
5+
var list = [Int](), stack = [TreeNode](), p = root
6+
7+
while p != nil || !stack.isEmpty {
8+
if let t = p {
9+
stack.append(t)
10+
p = t.left
11+
} else {
12+
let t = stack.popLast()!
13+
list.append(t.val)
14+
p = t.right
15+
}
16+
}
17+
18+
return list
19+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// 96. Unique Binary Search Trees
2+
// 8 ms
3+
4+
func numTrees(_ n: Int) -> Int {
5+
list = Array(repeating: 1, count: n+1)
6+
if n >= 2 { list[2] = 2 }
7+
return g(n)
8+
}
9+
10+
private var list: [Int]!
11+
private func g(_ n: Int) -> Int {
12+
if n > 2 && list[n] == 1 {
13+
list[n] = (1...n).reduce(0) { $0 + f($1, n) }
14+
}
15+
return list[n]
16+
}
17+
18+
private func f(_ i: Int, _ n: Int) -> Int {
19+
return g(i-1) * g(n-i)
20+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// 98. Validate Binary Search Tree
2+
// 28 ms, 100%
3+
4+
func isValidBST(_ root: TreeNode?) -> Bool {
5+
return isValidNode(root, Int.min, Int.max)
6+
}
7+
8+
private func isValidNode(_ root: TreeNode?, _ min: Int, _ max: Int) -> Bool {
9+
guard let p = root else { return true }
10+
if p.val >= max || p.val <= min { return false }
11+
return isValidNode(p.left, min, p.val) && isValidNode(p.right, p.val, max)
12+
}

0 commit comments

Comments
 (0)