-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommonstring.js
69 lines (58 loc) · 1.41 KB
/
Commonstring.js
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
function commonString(list1, list2) {
const map1 = new Map();
const map2 = new Map();
const result = [];
let minSum = Infinity;
for (let i = 0; i < list1.length; i++) {
if (!map1.has(list1[i])) {
map1.set(list1[i], i);
}
}
for (let i = 0; i < list2.length; i++) {
if (!map2.has(list2[i])) {
map2.set(list2[i], i);
}
}
for (const str of list1) {
if (map2.has(str)) {
const sum = map1.get(str) + map2.get(str);
if (sum < minSum) {
result.length = 0;
result.push(str);
minSum = sum;
} else if (sum === minSum) {
result.push(str);
}
}
}
return result;
}
function commonStrings(list1, list2) {
const map1 = {};
const map2 = {};
const result = [];
let minSum = Infinity;
for (let i = 0; i < list1.length; i++) {
if (!map1[list1[i]]) {
map1[list1[i]] = i;
}
}
for (let i = 0; i < list2.length; i++) {
if (!map2[list2[i]]) {
map2[list2[i]] = i;
}
}
for (const str of list1) {
if (map2[str] !== undefined) {
const sum = map1[str] + map2[str];
if (sum < minSum) {
result.length = 0;
result.push(str);
minSum = sum;
} else if (sum === minSum) {
result.push(str);
}
}
}
return result;
}