forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2306-naming-a-company.kt
50 lines (40 loc) · 1.34 KB
/
2306-naming-a-company.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
class Solution {
fun distinctNames(ideas: Array<String>): Long {
val firstToSuffix = Array(26) { hashSetOf<String>() }
var res = 0L
ideas.forEach {
firstToSuffix[it[0] - 'a'].add(it.substring(1, it.length))
}
for (i in 0 until 26) {
for (j in i until 26) {
val common = firstToSuffix[i].intersect(firstToSuffix[j]).size
val mapI = firstToSuffix[i].size - common
val mapJ = firstToSuffix[j].size - common
res += (mapI * mapJ) * 2
}
}
return res
}
}
// without using kotlins intersect() funtions
class Solution {
fun distinctNames(ideas: Array<String>): Long {
val firstToSuffix = Array(26) { hashSetOf<String>() }
var res = 0L
ideas.forEach {
firstToSuffix[it[0] - 'a'].add(it.substring(1, it.length))
}
for (i in 0 until 26) {
for (j in i until 26) {
var common = 0
for(wordA in firstToSuffix[i]) {
if(wordA in firstToSuffix[j]) common++
}
val mapI = firstToSuffix[i].size - common
val mapJ = firstToSuffix[j].size - common
res += (mapI * mapJ) * 2
}
}
return res
}
}