Home > database >  Remove a substring to make given word in javascript
Remove a substring to make given word in javascript

Time:08-21

I want to know about the algorithm for below question in JavaScript.

Check whether the given word can be "programming" or not by removing the substring between them. You can only remove one substring from the given the word. Give answer in 'yes' and 'no'

example                   answer      explanation
"progabcramming"            yes        remove substring 'abc'
"programmmeding"            yes         remove substring 'med'
"proasdgrammiedg"           no         u have to remove 2 subtring 'asd' and 'ied'
                                         which is not allowed
"pxrogramming"              yes           remove substring 'x'
"pxrogramminyg"              no           u have to remove 2 subtring 'x' and 'y'
                                         which is not allowed
     

Please tell me an algorithm to solve it

CodePudding user response:

{
  // will create a regexp for fuzzy search
  const factory = (str) => new RegExp(str.split('').join('(.*?)'), 'i')
  
  const re = factory('test') // re = /t(.*?)e(.*?)s(.*?)t/i
  const matches = re.exec('te-abc-st') ?? [] // an array of captured groups
  const result = matches
    .slice(1) // first element is a full match, we don't need it
    .filter(group => group.length) // we're  also not interested in empty matches
  // now result contains a list of captured groups 
  // in this particular example a single '-abc-'
}

CodePudding user response:

I'm not sure how efficient this code is, but only thing i can come up with is using regular expression.

const regexp = /^(p). (rogramming)|(pr). (ogramming)|(pro). (gramming)|(prog). (ramming)|(progr). (amming)|(progra). (mming)|(program). (ming)|(programm). (ing)|(programmi). (ng)|(programmin). (g)$/;

const test = ['progabcramming', 'programmmeding', 'proasdgrammiedg', 'pxrogramming', 'pxrogramminyg', 'programming'];

let text = '';
test.forEach(element => {
    text  = `${element}: ${regexp.test(element)}\n`;
});

document.body.innerText = text;

  • Related