mercredi 6 avril 2016

How to verify whether input 2 can be constructed using words in input 1 using Java?

Let's say we are given two text inputs. "input1" is a page in a novel. "input 2" is a random sentence "How do you do?". I need to verify whether this input 2 can be constructed using words in input1. Only solution I could come up with for this problem is like this.

step 0: create a boolean flag and set is value to true.

step1: Split first input into tokens and store the number of times each word occurs in a hashmap.

step2: Split second input into tokens and iterate through the tokens.

step3: Inside the loop, check whether the current token exists in the map. If not, set the boolean flag to false and exit the loop. If yes, check the value of the entry returned from Map. If it is zero, set the boolean flag to false and exit the loop. If the value is one or more, decrease it by 1 and continue the loop.

step4: Once the loop is done, return the value of the boolean flag.

As you can see, step1 and step 3 could take a long time if the inputs are big. What are the alternative methods to solve this problem which can have better run time?




Aucun commentaire:

Enregistrer un commentaire