Skip to content

Commit ae0779c

Browse files
authored
Merge pull request #2129 from a93a/main
Create 0014-longest-common-prefix.kt
2 parents c16eb96 + d7bee74 commit ae0779c

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

Diff for: kotlin/0014-longest-common-prefix.kt

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
* Solution as per the channel
3+
*/
4+
class Solution {
5+
fun longestCommonPrefix(strs: Array<String>): String {
6+
var len = 0
7+
outerloop@ for(i in 0 until strs[0].length){
8+
for(s in strs){
9+
if(i == s.length || s[i] != strs[0][i]){
10+
break@outerloop
11+
}
12+
}
13+
len++
14+
}
15+
return strs[0].substring(0,len)
16+
}
17+
}
18+
19+
/*
20+
* Same solution as above but a little more in an idiomatic Kotlin way
21+
*/
22+
class Solution {
23+
fun longestCommonPrefix(strs: Array<String>): String {
24+
var res = ""
25+
strs.minBy { it.length }?.forEachIndexed { i,c ->
26+
if(strs.all { it[i] == c } ) res += c else return res
27+
}
28+
return res
29+
}
30+
}
31+
32+
/*
33+
* Trie solution
34+
*/
35+
class TrieNode() {
36+
val child = arrayOfNulls<TrieNode>(26)
37+
var isEnd = false
38+
fun childCount() = this.child?.filter{it != null}?.count()
39+
}
40+
41+
class Solution {
42+
fun longestCommonPrefix(strs: Array<String>): String {
43+
44+
val root: TrieNode? = TrieNode()
45+
46+
for(word in strs) {
47+
var current = root
48+
for(c in word){
49+
if(current?.child?.get(c - 'a') == null){
50+
current?.child?.set(c - 'a', TrieNode())
51+
}
52+
current = current?.child?.get(c - 'a')
53+
}
54+
current?.isEnd = true
55+
}
56+
57+
var current = root
58+
var len = 0
59+
for (c in strs[0]){
60+
println(c)
61+
if (current?.childCount() == 1 && current?.isEnd != true) len++ else break
62+
current = current?.child?.get(c - 'a')
63+
}
64+
println(len)
65+
return strs[0].substring(0,len)
66+
}
67+
}
68+
69+
/*
70+
* Sorting solution
71+
*/
72+
class Solution {
73+
fun longestCommonPrefix(strs: Array<String>): String {
74+
var len = 0
75+
strs.sort()
76+
val first = strs[0]
77+
val last = strs[strs.size-1]
78+
val minLen = strs.minBy {it.length}?.length!!
79+
for(i in 0 until minLen){
80+
if(first[i] == last[i]) len++ else break
81+
}
82+
return strs[0].substring(0,len)
83+
}
84+
}

0 commit comments

Comments
 (0)