From e0f56b332bb7bd5ba391de7b235f3da9e7abe739 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Tue, 19 Nov 2024 07:28:09 +0100 Subject: [PATCH] feat: add swift implementation to lcp problem: No.44 --- .../README.md" | 32 +++++++++++++++++++ .../Solution.swift" | 27 ++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 "lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/Solution.swift" diff --git "a/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/README.md" "b/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/README.md" index 7add041f2ff7d..b1796c3665ec6 100644 --- "a/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/README.md" +++ "b/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/README.md" @@ -159,6 +159,38 @@ func dfs(root *TreeNode) { } ``` +#### Swift + +```swift +/* class TreeNode { +* var val: Int +* var left: TreeNode? +* var right: TreeNode? +* init(_ val: Int) { +* self.val = val +* self.left = nil +* self.right = nil +* } +* } +*/ + +class Solution { + private var uniqueColors: Set = [] + + func numColor(_ root: TreeNode?) -> Int { + dfs(root) + return uniqueColors.count + } + + private func dfs(_ node: TreeNode?) { + guard let node = node else { return } + uniqueColors.insert(node.val) + dfs(node.left) + dfs(node.right) + } +} +``` + diff --git "a/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/Solution.swift" "b/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/Solution.swift" new file mode 100644 index 0000000000000..b1381f7de3fa0 --- /dev/null +++ "b/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/Solution.swift" @@ -0,0 +1,27 @@ +/* class TreeNode { +* var val: Int +* var left: TreeNode? +* var right: TreeNode? +* init(_ val: Int) { +* self.val = val +* self.left = nil +* self.right = nil +* } +* } +*/ + +class Solution { + private var uniqueColors: Set = [] + + func numColor(_ root: TreeNode?) -> Int { + dfs(root) + return uniqueColors.count + } + + private func dfs(_ node: TreeNode?) { + guard let node = node else { return } + uniqueColors.insert(node.val) + dfs(node.left) + dfs(node.right) + } +} \ No newline at end of file