forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0014-longest-common-prefix.kt
84 lines (77 loc) · 2.08 KB
/
0014-longest-common-prefix.kt
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
77
78
79
80
81
82
83
84
/*
* Solution as per the channel
*/
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
var len = 0
outerloop@ for(i in 0 until strs[0].length){
for(s in strs){
if(i == s.length || s[i] != strs[0][i]){
break@outerloop
}
}
len++
}
return strs[0].substring(0,len)
}
}
/*
* Same solution as above but a little more in an idiomatic Kotlin way
*/
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
var res = ""
strs.minBy { it.length }?.forEachIndexed { i,c ->
if(strs.all { it[i] == c } ) res += c else return res
}
return res
}
}
/*
* Trie solution
*/
class TrieNode() {
val child = arrayOfNulls<TrieNode>(26)
var isEnd = false
fun childCount() = this.child?.filter{it != null}?.count()
}
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
val root: TrieNode? = TrieNode()
for(word in strs) {
var current = root
for(c in word){
if(current?.child?.get(c - 'a') == null){
current?.child?.set(c - 'a', TrieNode())
}
current = current?.child?.get(c - 'a')
}
current?.isEnd = true
}
var current = root
var len = 0
for (c in strs[0]){
println(c)
if (current?.childCount() == 1 && current?.isEnd != true) len++ else break
current = current?.child?.get(c - 'a')
}
println(len)
return strs[0].substring(0,len)
}
}
/*
* Sorting solution
*/
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
var len = 0
strs.sort()
val first = strs[0]
val last = strs[strs.size-1]
val minLen = strs.minBy {it.length}?.length!!
for(i in 0 until minLen){
if(first[i] == last[i]) len++ else break
}
return strs[0].substring(0,len)
}
}