title: Finding Sub-Strings of String Containing all the words in array
body: <p>I have a String and an array of words and I have to write code to find all substrings of the string that contain all the words in the array in any order. The string does not contain any special characters / digits and each word is separated by a space.</p>
  
  <p>For example:</p>
  
  <p><strong>String given:</strong></p>
  
  <pre><code>aaaa aaaa aaaa aaaa cccc bbbb bbbb bbbb bbbb aaaa bbbb cccc
  </code></pre>
  
  <p><strong>Words in array:</strong></p>
  
  <pre><code>aaaa
  bbbb
  cccc
  </code></pre>
  
  <p><strong>Sample of output:</strong></p>
  
  <pre><code>aaaa aaaa aaaa aaaa cccc bbbb bbbb bbbb bbbb    
  
  aaaa aaaa aaaa aaaa cccc bbbb    
  
  aaaa cccc bbbb bbbb bbbb bbbb    
  
  cccc bbbb bbbb bbbb bbbb aaaa  
  
  aaaa cccc bbbb
  </code></pre>
  
  <p>I have implemented this using for loops, but this is very inefficient.</p>
  
  <p>How can I do this more efficiently?</p>
  
  <p><strong>My code:</strong></p>
  
  <pre><code>    for(int i=0;i&lt;str_arr.length;i++)
      {
          if( (str_arr.length - i) &gt;= words.length)
          {
              String res = check(i);
              if(!res.equals(""))
              {
                  System.out.println(res);
                  System.out.println("");
              }
              reset_all();
          }
          else
          {
              break;
          }
      }
  
  public static String check(int i)
  {
      String res = "";
      num_words = 0;
  
      for(int j=i;j&lt;str_arr.length;j++)
      {
          if(has_word(str_arr[j]))
          {
              t.put(str_arr[j].toLowerCase(), 1);
              h.put(str_arr[j].toLowerCase(), 1);
  
              res = res + str_arr[j]; //+ " ";
  
              if(all_complete())
              {
                  return res;
              }
  
              res = res + " ";
          }
          else
          {
              res = res + str_arr[j] + " ";
          }
  
      }
      res = "";
      return res;
  }
  </code></pre>