-2

Say you have an array of words

String[] arr = {"i", "a", "am", "good", "program", "gram"};

And a given key

String key = "iamgood";

boolean allWordsFound(arr, key){

// should return true if all possible words from array make up the key.
// e.g. keys matched {"i", "am", "good"};

} 

My approach :

boolean workbreak(String[] arr, String key) {

StringBuilder tempStr = new StringBuilder();
String[] possibleValues;
int count = 0;

 for(i = 0; i < key.length()- 1; i++){
     tempStr.append(key[i]);
     for(j =0; j < arr.length(); j++){
         tempStr == arr[j]{
             return true;
             //possibleValues[count] = tempStr;
             //count++;
         }
     }
 }

}

I am unable to figure out an approach. I do not need code but can you please suggest an algorithm.

5
  • did you try anything to solve it by yourself? Commented Nov 17, 2016 at 20:04
  • @bart.s Yes I did, My approach was to run a loop on key and create all possible sub strings. Then check if those sub strings are present in the array. But the problem is I am unable to decide how to use the appropriate key. Eg : how to discard "a" and instead use "am" Commented Nov 17, 2016 at 20:12
  • paste your code in the problem description, so that we could revise your solution, and write exactly what are your doubts there. If we can't see your input, and there is no detailed description, we won't be able to help you. Commented Nov 17, 2016 at 20:15
  • @bart.s updated the description. I am not looking for code. But more of an approach. Thank you Commented Nov 17, 2016 at 20:23
  • The first thing that comes to my mind is to generate all possible permutations from the String array (arr) and check if the list of permutations contains a given word. When I find some other idea, I will get back to you. Commented Nov 17, 2016 at 20:31

1 Answer 1

1

Try the following:

Sort the String array by length, from longest to shortest:

{"i", "a", "am", "good", "program", "gram"};

becomes:

{"program","gram","good","am","a","i"}

The idea here is to match the longer words first, since in a case like this, you would want to match 'am' first before matching with 'a' (using the contains function).

Thus, the algorithm would check "program", then "gram", then "good" (matches), then "am" (matches), then "a", then "i" (matches).

The other solution is like bart.s stated in the comments: find all permutations, then check if any certain one matches. That will be a very slow algorithm though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.