File tree Expand file tree Collapse file tree 1 file changed +14
-15
lines changed Expand file tree Collapse file tree 1 file changed +14
-15
lines changed Original file line number Diff line number Diff line change 4
4
* @return {string }
5
5
*/
6
6
const boldWords = function ( words , S ) {
7
- const boldMap = new Array ( S . length ) . fill ( 0 )
8
- for ( let i = 0 ; i < words . length ; i ++ ) {
9
- let match = - 1
10
- while ( ( match = S . indexOf ( words [ i ] , match + 1 ) ) > - 1 ) {
11
- for ( let j = match ; j < match + words [ i ] . length ; j ++ ) {
12
- boldMap [ j ] = 1
7
+ const arr = new Array ( S . length ) . fill ( false )
8
+ for ( let w of words ) {
9
+ for ( let i = 0 , len = S . length - w . length ; i <= len ; i ++ ) {
10
+ const tmp = S . slice ( i )
11
+ if ( tmp && tmp . startsWith ( w ) ) {
12
+ for ( let j = i ; j < i + w . length ; j ++ ) {
13
+ arr [ j ] = true
14
+ }
13
15
}
14
16
}
15
17
}
16
18
let res = ''
17
- let openTag = false
18
- for ( let i = 0 ; i < S . length ; i ++ ) {
19
- if ( boldMap [ i ] && ! openTag ) {
20
- res += `<b>`
21
- openTag = true
22
- } else if ( ! boldMap [ i ] && openTag ) {
23
- res += `</b>`
24
- openTag = false
19
+ for ( let i = 0 , len = S . length ; i < len ; i ++ ) {
20
+ if ( arr [ i ] && ( i === 0 || ! arr [ i - 1 ] ) ) {
21
+ res += '<b>'
25
22
}
26
23
res += S [ i ]
24
+ if ( arr [ i ] && ( i === len - 1 || ! arr [ i + 1 ] ) ) {
25
+ res += '</b>'
26
+ }
27
27
}
28
- res += openTag ? `</b>` : ``
29
28
return res
30
29
}
You can’t perform that action at this time.
0 commit comments