Can the string be segmented in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are given a non−empty string str and an array of strings arr containing a list of non−empty words.

We are required to write a function that determines if str can be segmented into a spaceseparated sequence of one or more words that exist in the array.

Note

  • The same word in the array may be reused multiple times in the segmentation.

  • The array does not contain duplicate words.

Example 1

If the input is

const str = "applepenapple";
const arr = ["apple", "pen"];

The output should be true, because

"applepenapple" can be segmented as "apple pen apple".

Example

The code for this will be −

const str = "applepenapple";
const arr = ["apple", "pen"];
const wordSequence = (str = '', arr = []) => {
   const map = {}
   function helper(str) {
      if (map.hasOwnProperty(str)) {
         return map[str]
      } else if (str=='') {
         return true
      }
      for (let i=0;i<=str.length;i++) {
         if (
            arr.includes(str.slice(i)) &&
            helper(str.slice(0, i))
         ){
            map[str] = true
            return true
         }
      };
      map[str] = false;
      return false;
   };
   return helper(str)
};
console.log(wordSequence(str, arr));

Output

And the output in the console will be −

true
raja
Published on 21-Nov-2020 10:22:08
Advertisements