MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / isAbbreviation

Function isAbbreviation

Dynamic-Programming/Abbreviation.js:15–47  ·  view source on GitHub ↗
(source, target)

Source from the content-addressed store, hash-verified

13 * @see https://www.hackerrank.com/challenges/abbr/problem - Related problem on HackerRank.
14 */
15export const isAbbreviation = (source, target) => {
16 const sourceLength = source.length
17 const targetLength = target.length
18
19 // Initialize a table to keep track of possible abbreviations
20 let canAbbreviate = Array.from({ length: sourceLength + 1 }, () =>
21 Array(targetLength + 1).fill(false)
22 )
23 // Empty strings are trivially abbreviatable
24 canAbbreviate[0][0] = true
25
26 for (let sourceIndex = 0; sourceIndex < sourceLength; sourceIndex++) {
27 for (let targetIndex = 0; targetIndex <= targetLength; targetIndex++) {
28 if (canAbbreviate[sourceIndex][targetIndex]) {
29 // If characters at the current position are equal, move to the next position in both strings.
30 if (
31 targetIndex < targetLength &&
32 source[sourceIndex].toUpperCase() === target[targetIndex]
33 ) {
34 canAbbreviate[sourceIndex + 1][targetIndex + 1] = true
35 }
36 // If the current character in `source` is lowercase, explore two possibilities:
37 // a) Capitalize it (which is akin to "using" it in `source` to match `target`), or
38 // b) Skip it (effectively deleting it from `source`).
39 if (source[sourceIndex] === source[sourceIndex].toLowerCase()) {
40 canAbbreviate[sourceIndex + 1][targetIndex] = true
41 }
42 }
43 }
44 }
45
46 return canAbbreviate[sourceLength][targetLength]
47}

Callers 2

expectPositiveFunction · 0.90
expectNegativeFunction · 0.90

Calls

no outgoing calls

Tested by 2

expectPositiveFunction · 0.72
expectNegativeFunction · 0.72