File tree 1 file changed +9
-8
lines changed
scripts/algorithms/S/Shortest Completing Word
1 file changed +9
-8
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 102 ms (Top 73.77%) | Memory: 44.2 MB (Top 95.08%)
1
2
var shortestCompletingWord = function ( licensePlate , words ) {
2
-
3
+
3
4
// Object to hold the shortest word that matches
4
5
var match = { 'found' :false , 'word' :'' } ;
5
-
6
+
6
7
// Char array to hold the upper case characters we want to match
7
8
var licensePlateChars = licensePlate . toUpperCase ( ) . replace ( / [ ^ A - Z ] / g, '' ) . split ( '' ) ;
8
-
9
+
9
10
words . forEach ( function ( word ) {
10
11
// if we already have a match make sure that the word we are checking is shorter
11
12
if ( ! match . found || word . length < match . word . length ) {
12
13
var replaceWord = word . toUpperCase ( ) ;
13
-
14
+
14
15
// Loop over each character in the license plate and replace one at a time
15
16
// the key here is that replace will only replace 1 S even if there are 2
16
17
licensePlateChars . forEach ( function ( lChar ) {
17
18
replaceWord = replaceWord . replace ( lChar , '' ) ;
18
19
} ) ;
19
-
20
- // We know the word works if the length of the word minus
20
+
21
+ // We know the word works if the length of the word minus
21
22
// the length of chars equals the length of the new word
22
23
if ( word . length - licensePlateChars . length === replaceWord . length ) {
23
24
match . found = true ;
24
25
match . word = word
25
26
}
26
27
}
27
28
} ) ;
28
-
29
+
29
30
return match . word ;
30
- } ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments