-
Notifications
You must be signed in to change notification settings - Fork 225
/
1055-shortest-way-to-form-string,js
53 lines (49 loc) · 1.09 KB
/
1055-shortest-way-to-form-string,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
/**
* @param {string} source
* @param {string} target
* @return {number}
*/
const shortestWay = function(source, target) {
const a = 'a'.charCodeAt(0), arr = Array(26).fill(0)
for(const ch of source) arr[ch.charCodeAt(0) - a] = 1
let res = 0, j = 0
for(let i = 0, n = source.length; i < n; i++) {
if(arr[target[j].charCodeAt(0) - a] === 0) return -1
if(source[i] === target[j]) j++
if(j === target.length) {
res++
break
}
if(i === n - 1) {
res++
i = -1
}
}
return res
};
// another
/**
* @param {string} source
* @param {string} target
* @return {number}
*/
const shortestWay = function(source, target) {
const a = 'a'.charCodeAt(0), map = Array(26).fill(0)
for(let ch of source) {
map[ch.charCodeAt(0) - a] = 1
}
let j = 0, res = 1
for(let i = 0, n = target.length; i < n; i++, j++) {
const cur = target[i]
if(map[cur.charCodeAt(0) - a] === 0) return -1
while(j < source.length && source[j] !== cur) {
j++
}
if(j === source.length) {
res++
j = -1
i--
}
}
return res
};