File tree 4 files changed +106
-0
lines changed
best-time-to-buy-and-sell-stock
implement-trie-prefix-tree
4 files changed +106
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func maxProfit( _ prices: [ Int ] ) -> Int {
3
+ guard var anchor = prices. first, prices. count > 1 else {
4
+ return 0
5
+ }
6
+
7
+ var result = 0
8
+ for price in prices {
9
+ if price < anchor {
10
+ anchor = price
11
+ } else if price - anchor > result {
12
+ result = price - anchor
13
+ }
14
+ }
15
+
16
+ return result
17
+ }
18
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func groupAnagrams( _ strs: [ String ] ) -> [ [ String ] ] {
3
+ var groups : [ String : [ String ] ] = [ : ]
4
+
5
+ for str in strs {
6
+ let sortedStr = String ( str. sorted ( ) )
7
+
8
+ var values = groups [ sortedStr] ?? [ ]
9
+ values. append ( str)
10
+
11
+ groups [ sortedStr] = values
12
+ }
13
+
14
+ return Array ( groups. values)
15
+ }
16
+ }
Original file line number Diff line number Diff line change
1
+ class TrieNode {
2
+ var children : [ Character : TrieNode ] = [ : ]
3
+ var isEnd : Bool = false
4
+ }
5
+
6
+ class Trie {
7
+ private let root : TrieNode
8
+
9
+ init ( ) {
10
+ root = TrieNode ( )
11
+ }
12
+
13
+ func insert( _ word: String ) {
14
+ var current = root
15
+ for char in word {
16
+ if current. children [ char] == nil {
17
+ current. children [ char] = TrieNode ( )
18
+ }
19
+ current = current. children [ char] !
20
+ }
21
+ current. isEnd = true
22
+ }
23
+
24
+ func search( _ word: String ) -> Bool {
25
+ guard let node = findNode ( word) else {
26
+ return false
27
+ }
28
+ return node. isEnd
29
+ }
30
+
31
+ func startsWith( _ prefix: String ) -> Bool {
32
+ return findNode ( prefix) != nil
33
+ }
34
+
35
+ private func findNode( _ prefix: String ) -> TrieNode ? {
36
+ var current = root
37
+ for char in prefix {
38
+ guard let next = current. children [ char] else {
39
+ return nil
40
+ }
41
+ current = next
42
+ }
43
+ return current
44
+ }
45
+ }
46
+
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func wordBreak( _ s: String , _ wordDict: [ String ] ) -> Bool {
3
+ let wordSet = Set ( wordDict)
4
+ var dp = Array ( repeating: false , count: s. count + 1 )
5
+
6
+ dp [ 0 ] = true
7
+
8
+ for i in 1 ... s. count {
9
+ for j in 0 ..< i {
10
+
11
+ guard dp [ j] else { continue }
12
+
13
+ let startIndex = s. index ( s. startIndex, offsetBy: j)
14
+ let endIndex = s. index ( s. startIndex, offsetBy: i)
15
+ let word = String ( s [ startIndex..< endIndex] )
16
+
17
+ if wordSet. contains ( word) {
18
+ dp [ i] = true
19
+ break
20
+ }
21
+ }
22
+ }
23
+
24
+ return dp [ s. count]
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments