Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's my solution in C++:</p> <pre><code>int min_width(const string&amp; x, const set&lt;char&gt;&amp; y) { vector&lt;int&gt; at; for (int i = 0; i &lt; x.length(); i++) if (y.count(x[i]) &gt; 0) at.push_back(i); int ret = x.size(); int start = 0; map&lt;char, int&gt; count; for (int end = 0; end &lt; at.size(); end++) { count[x[at[end]]]++; while (count[x[at[start]]] &gt; 1) count[x[at[start++]]]--; if (count.size() == y.size() &amp;&amp; ret &gt; at[end] - at[start] + 1) ret = at[end] - at[start] + 1; } return ret; } </code></pre> <p><strong>Edit</strong>: Here's an implementation of Jack's idea. It's the same time complexity as mine, but without the inner loop that confuses you.</p> <pre><code>int min_width(const string&amp; x, const set&lt;char&gt;&amp; y) { int ret = x.size(); map&lt;char, int&gt; index; set&lt;int&gt; index_set; for (int j = 0; j &lt; x.size(); j++) { if (y.count(x[j]) &gt; 0) { if (index.count(x[j]) &gt; 0) index_set.erase(index[x[j]]); index_set.insert(j); index[x[j]] = j; if (index.size() == y.size()) { int i = *index_set.begin(); if (ret &gt; j-i+1) ret = j-i+1; } } } return ret; } </code></pre> <p>In Java it can be implemented nicely with LinkedHashMap:</p> <pre><code>static int minWidth(String x, HashSet&lt;Character&gt; y) { int ret = x.length(); Map&lt;Character, Integer&gt; index = new LinkedHashMap&lt;Character, Integer&gt;(); for (int j = 0; j &lt; x.length(); j++) { char ch = x.charAt(j); if (y.contains(ch)) { index.remove(ch); index.put(ch, j); if (index.size() == y.size()) { int i = index.values().iterator().next(); if (ret &gt; j - i + 1) ret = j - i + 1; } } } return ret; } </code></pre> <p>All operations inside the loop take constant time (assuming hashed elements disperse properly). </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload