How to print the dictionary words in the output for the given word using javascript

Viewed 2504

I Have the function WordSplit(strArr) which has to read the array of strings stored in strArr, which will contain 2 elements: the first element will be a sequence of characters, and the second element will be a long string of comma-separated words, in alphabetical order, that represents a dictionary of some arbitrary length.

For example: strArr can be: ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]. My goal is to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input. In this example, the first element can be split into two words: hello and cat because both of those words are in the dictionary.

2 Answers

You can create a Set from the dictionary (after splitting on a comma) and then test every single splitting point, checking if the two words obtained at each point exist in the Set.

function WordSplit([word, dictionary]) {
  dictionary = new Set(dictionary.split(","));
  for (let i = 0; i < word.length; i++) {
    if (dictionary.has(word.slice(0, i)) && dictionary.has(word.slice(i))) {
      console.log(word, 'can be split into', word.slice(0, i), 'and', word.slice(i));
      return true;
    }
  }
  return false;
}
console.log(WordSplit(["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]));

The only way I can think of doing it is having a String Array of dictionary words. This obviously wouldn't be as comprehensive, and sort of laborious. You could check each word in strArr against each of your words in your String Array of dictionary words using a for loop, and if the word in strArr contains any dictionary word using the contains method, then you could split the word in strArr into two parts: part1 going from charAt 0 in str[i] until the CharSequence s, and part2 going from s to the end of str[i].

 for(int i = 0; i < strArr.length; i++) {
    
        for (int x = 0; x < words.length; x++) {

 CharSequence s = words[x]
    if(strArr[i].contains(s) {
    String part1 = strArr[i].split(0,s);
    String part2 = strArr[i].split(s);
    }
    System.out.println(part1 + "" + part2);
}

}

Related