File tree Expand file tree Collapse file tree 3 files changed +87
-0
lines changed
best-time-to-buy-and-sell-stock
implement-trie-prefix-tree Expand file tree Collapse file tree 3 files changed +87
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode_study
2+
3+ import kotlin.math.max
4+ import kotlin.math.min
5+ fun maxProfit (prices : IntArray ): Int {
6+ var minPrice = prices[0 ]
7+ var maxProfit = 0
8+
9+ for (i in 0 until prices.size) {
10+ maxProfit = max(maxProfit, prices[i] - minPrice)
11+ minPrice = min(minPrice, prices[i])
12+ }
13+
14+ return maxProfit
15+ }
Original file line number Diff line number Diff line change 1+ package leetcode_study
2+
3+ fun groupAnagrams (strs : Array <String >): List <List <String >> {
4+ val anagrams = HashMap <String , MutableList <String >>()
5+ strs.forEach { str ->
6+ val chars = str.toCharArray().sorted()
7+ anagrams.putIfAbsent(chars.toString(), mutableListOf ())
8+ val words = anagrams[chars.toString()]
9+ words?.add(str)
10+ }
11+
12+ return anagrams.values.toList()
13+ }
Original file line number Diff line number Diff line change 1+ package leetcode_study
2+
3+ class FirstSolution {
4+ private val document = hashSetOf<String >()
5+
6+ fun insert (word : String ) {
7+ document.add(word)
8+ }
9+
10+ fun search (word : String ): Boolean {
11+ return document.contains(word)
12+ }
13+
14+ fun startsWith (prefix : String ): Boolean {
15+ val word = document.firstOrNull { it.startsWith(prefix) }
16+ return word != null
17+ }
18+ }
19+
20+ class SecondSolution {
21+ class Document (var end : Boolean = true ) {
22+ val items = hashMapOf<Char , Document >()
23+ }
24+
25+ private val document = Document (end = true )
26+
27+ fun insert (word : String ) {
28+ var node = document
29+ for (char in word) {
30+ if (char !in node.items) {
31+ node.items[char] = Document (end = false )
32+ }
33+ node = node.items[char]!!
34+ }
35+ node.end = true
36+ }
37+
38+ fun search (word : String ): Boolean {
39+ var node = document
40+ for (char in word) {
41+ if (char !in node.items) {
42+ return false
43+ }
44+ node = node.items[char]!!
45+ }
46+ return node.end
47+ }
48+
49+ fun startsWith (prefix : String ): Boolean {
50+ var node = document
51+ for (char in prefix) {
52+ if (char !in node.items) {
53+ return false
54+ }
55+ node = node.items[char]!!
56+ }
57+ return true
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments