<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>substring Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/substring/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/substring/</link>
	<description></description>
	<lastBuildDate>Sun, 15 May 2022 19:02:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>substring Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/substring/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2269. Find the K-Beauty of a Number</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2269-find-the-k-beauty-of-a-number/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2269-find-the-k-beauty-of-a-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 May 2022 19:01:07 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9741</guid>

					<description><![CDATA[<p>The&#160;k-beauty&#160;of an integer&#160;num&#160;is defined as the number of&#160;substrings&#160;of&#160;num&#160;when it is read as a string that meet the following conditions: It has a length of&#160;k. It&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-2269-find-the-k-beauty-of-a-number/">花花酱 LeetCode 2269. Find the K-Beauty of a Number</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>The&nbsp;<strong>k-beauty</strong>&nbsp;of an integer&nbsp;<code>num</code>&nbsp;is defined as the number of&nbsp;<strong>substrings</strong>&nbsp;of&nbsp;<code>num</code>&nbsp;when it is read as a string that meet the following conditions:</p>



<ul><li>It has a length of&nbsp;<code>k</code>.</li><li>It is a divisor of&nbsp;<code>num</code>.</li></ul>



<p>Given integers&nbsp;<code>num</code>&nbsp;and&nbsp;<code>k</code>, return&nbsp;<em>the k-beauty of&nbsp;</em><code>num</code>.</p>



<p>Note:</p>



<ul><li><strong>Leading zeros</strong>&nbsp;are allowed.</li><li><code>0</code>&nbsp;is not a divisor of any value.</li></ul>



<p>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous sequence of characters in a string.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 240, k = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> The following are the substrings of num of length k:
- "24" from "<strong><u>24</u></strong>0": 24 is a divisor of 240.
- "40" from "2<strong>40</strong>": 40 is a divisor of 240.
Therefore, the k-beauty is 2.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 430043, k = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> The following are the substrings of num of length k:
- "43" from "<strong>43</strong>0043": 43 is a divisor of 430043.
- "30" from "4<strong>30</strong>043": 30 is not a divisor of 430043.
- "00" from "43<strong>00</strong>43": 0 is not a divisor of 430043.
- "04" from "430<strong>04</strong>3": 4 is not a divisor of 430043.
- "43" from "4300<strong>43</strong>": 43 is a divisor of 430043.
Therefore, the k-beauty is 2.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= num &lt;= 10<sup>9</sup></code></li><li><code>1 &lt;= k &lt;= num.length</code>&nbsp;(taking&nbsp;<code>num</code>&nbsp;as a string)</li></ul>



<h2><strong>Solution: Substring</strong></h2>



<p>Note: the substring can be 0, e.g. &#8220;00&#8221;</p>



<p>Time complexity: O((l-k)*k)<br>Space complexity: O(l + k) -&gt; O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int divisorSubstrings(int num, int k) {
    string s = to_string(num);
    int ans = 0;
    for (int i = 0; i &lt;= s.length() - k; ++i) {
      const int t = stoi(s.substr(i, k));
      ans += t &amp;&amp; (num % t == 0);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-2269-find-the-k-beauty-of-a-number/">花花酱 LeetCode 2269. Find the K-Beauty of a Number</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2269-find-the-k-beauty-of-a-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1946. Largest Number After Mutating Substring</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1946-largest-number-after-mutating-substring/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1946-largest-number-after-mutating-substring/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 20:32:39 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[replacing]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9314</guid>

					<description><![CDATA[<p>You are given a string&#160;num, which represents a large integer. You are also given a&#160;0-indexed&#160;integer array&#160;change&#160;of length&#160;10&#160;that maps each digit&#160;0-9&#160;to another digit. More formally, digit&#160;d&#160;maps&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1946-largest-number-after-mutating-substring/">花花酱 LeetCode 1946. Largest Number After Mutating Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a string&nbsp;<code>num</code>, which represents a large integer. You are also given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>change</code>&nbsp;of length&nbsp;<code>10</code>&nbsp;that maps each digit&nbsp;<code>0-9</code>&nbsp;to another digit. More formally, digit&nbsp;<code>d</code>&nbsp;maps to digit&nbsp;<code>change[d]</code>.</p>



<p>You may&nbsp;<strong>choose</strong>&nbsp;to&nbsp;<strong>mutate a single substring</strong>&nbsp;of&nbsp;<code>num</code>. To mutate a substring, replace each digit&nbsp;<code>num[i]</code>&nbsp;with the digit it maps to in&nbsp;<code>change</code>&nbsp;(i.e. replace&nbsp;<code>num[i]</code>&nbsp;with&nbsp;<code>change[num[i]]</code>).</p>



<p>Return&nbsp;<em>a string representing the&nbsp;<strong>largest</strong>&nbsp;possible integer after&nbsp;<strong>mutating</strong>&nbsp;(or choosing not to) a&nbsp;<strong>single substring</strong>&nbsp;of&nbsp;</em><code>num</code>.</p>



<p>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous sequence of characters within the string.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "132", change = [9,8,5,0,3,6,4,2,6,8]
<strong>Output:</strong> "832"
<strong>Explanation:</strong> Replace the substring "1":
- 1 maps to change[1] = 8.
Thus, "132" becomes "832".
"832" is the largest number that can be created, so return it.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "021", change = [9,4,3,5,7,2,1,9,0,6]
<strong>Output:</strong> "934"
<strong>Explanation:</strong> Replace the substring "021":
- 0 maps to change[0] = 9.
- 2 maps to change[2] = 3.
- 1 maps to change[1] = 4.
Thus, "021" becomes "934".
"934" is the largest number that can be created, so return it.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "5", change = [1,4,7,5,3,2,5,6,9,4]
<strong>Output:</strong> "5"
<strong>Explanation:</strong> "5" is already the largest number that can be created, so return it.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= num.length &lt;= 10<sup>5</sup></code></li><li><code>num</code>&nbsp;consists of only digits&nbsp;<code>0-9</code>.</li><li><code>change.length == 10</code></li><li><code>0 &lt;= change[d] &lt;= 9</code></li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Find the first digit that is less equal to the mutated one as the start of the substring, keep replacing as long as mutated &gt;= current.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string maximumNumber(string num, vector&lt;int&gt;&amp; change) {
    const int n = num.size();
    for (int i = 0; i &lt; n; ++i)
      if (num[i] - '0' &lt; change[num[i] - '0']) {
        for (int j = i; j &lt; n &amp;&amp; num[j] - '0' &lt;= change[num[j] - '0']; ++j)
          num[j] = change[num[j] - '0'] + '0';
        break;
      }
    return num;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1946-largest-number-after-mutating-substring/">花花酱 LeetCode 1946. Largest Number After Mutating Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-1946-largest-number-after-mutating-substring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1915. Number of Wonderful Substrings</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1915-number-of-wonderful-substrings/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1915-number-of-wonderful-substrings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Dec 2021 11:11:08 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[bitmask]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9230</guid>

					<description><![CDATA[<p>A&#160;wonderful&#160;string is a string where&#160;at most one&#160;letter appears an&#160;odd&#160;number of times. For example,&#160;"ccjjc"&#160;and&#160;"abab"&#160;are wonderful, but&#160;"ab"&#160;is not. Given a string&#160;word&#160;that consists of the first ten lowercase&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1915-number-of-wonderful-substrings/">花花酱 LeetCode 1915. Number of Wonderful Substrings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A&nbsp;<strong>wonderful</strong>&nbsp;string is a string where&nbsp;<strong>at most one</strong>&nbsp;letter appears an&nbsp;<strong>odd</strong>&nbsp;number of times.</p>



<ul><li>For example,&nbsp;<code>"ccjjc"</code>&nbsp;and&nbsp;<code>"abab"</code>&nbsp;are wonderful, but&nbsp;<code>"ab"</code>&nbsp;is not.</li></ul>



<p>Given a string&nbsp;<code>word</code>&nbsp;that consists of the first ten lowercase English letters (<code>'a'</code>&nbsp;through&nbsp;<code>'j'</code>), return&nbsp;<em>the&nbsp;<strong>number of wonderful non-empty substrings</strong>&nbsp;in&nbsp;</em><code>word</code><em>. If the same substring appears multiple times in&nbsp;</em><code>word</code><em>, then count&nbsp;<strong>each occurrence</strong>&nbsp;separately.</em></p>



<p>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous sequence of characters in a string.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "aba"
<strong>Output:</strong> 4
<strong>Explanation:</strong> The four wonderful substrings are underlined below:
- "<strong>a</strong>ba" -&gt; "a"
- "a<strong>b</strong>a" -&gt; "b"
- "ab<strong>a</strong>" -&gt; "a"
- "<strong>aba</strong>" -&gt; "aba"
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "aabb"
<strong>Output:</strong> 9
<strong>Explanation:</strong> The nine wonderful substrings are underlined below:
- "<strong><u>a</u></strong>abb" -&gt; "a"
- "<strong>aa</strong>bb" -&gt; "aa"
- "<strong>aab</strong>b" -&gt; "aab"
- "<strong>aabb</strong>" -&gt; "aabb"
- "a<strong>a</strong>bb" -&gt; "a"
- "a<strong>abb</strong>" -&gt; "abb"
- "aa<strong>b</strong>b" -&gt; "b"
- "aa<strong>bb</strong>" -&gt; "bb"
- "aab<strong>b</strong>" -&gt; "b"
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "he"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The two wonderful substrings are underlined below:
- "<strong><u>h</u></strong>e" -&gt; "h"
- "h<strong><u>e</u></strong>" -&gt; "e"
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li><li><code>word</code>&nbsp;consists of lowercase English letters from&nbsp;<code>'a'</code>&nbsp;to&nbsp;<code>'j'</code>.</li></ul>



<h2><strong>Solution: Prefix Bitmask + Hashtable</strong></h2>



<p>Similar to <a href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1371-find-the-longest-substring-containing-vowels-in-even-counts/" data-type="post" data-id="6400">花花酱 LeetCode 1371. Find the Longest Substring Containing Vowels in Even Counts</a>, we use   a bitmask to represent the occurrence (odd or even) of each letter and use a hashtable to store the frequency of each bitmask seen so far.<br><br>1. &#8220;0000000000&#8221; means all letters occur even times.<br>2. &#8220;0000000101&#8221; means <meta charset="utf-8">all letters occur even times expect letter &#8216;a&#8217; and &#8216;c&#8217; that occur odd times.</p>



<p>We scan the word from left to right and update the bitmask: bitmask ^= (1 &lt;&lt; (c-&#8216;a&#8217;)). <br>However, the bitmask only represents the state of the prefix, i.e. word[0:i], then how can we count substrings? The answer is hashtable.  If the same bitmask occurs c times before, which means there are c indices that word[0~j1], word[0~j2], &#8230;, word[0~jc] have the same state as word[0~i] that means for word[j1+1~i], word[j2+1~i], &#8230;, word[jc+1~i], all letters occurred even times. <br>For the &#8220;at most one odd&#8221; case, we toggle each bit of the bitmask and check how many times it occurred before.</p>



<p>ans += freq[mask] + sum(freq[mask ^ (1 &lt;&lt; i)] for i in range(k))</p>



<p>Time complexity: O(n*k)<br>Space complexity: O(2<sup>k</sup>)<br>where k = j &#8211; a + 1 = 10</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long wonderfulSubstrings(string word) {
    constexpr int l = 'j' - 'a' + 1;
    vector&lt;int&gt; count(1 &lt;&lt; l);
    count[0] = 1;
    int mask = 0;
    long long ans = 0;
    for (char c : word) {
      mask ^= 1 &lt;&lt; (c - 'a'); 
      for (int i = 0; i &lt; l; ++i)
        ans += count[mask ^ (1 &lt;&lt; i)]; // one odd.
      ans += count[mask]++; // all even.
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1915-number-of-wonderful-substrings/">花花酱 LeetCode 1915. Number of Wonderful Substrings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1915-number-of-wonderful-substrings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 30. Substring with Concatenation of All Words</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words-2/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words-2/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 27 Nov 2021 00:47:18 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8789</guid>

					<description><![CDATA[<p>You are given a string&#160;s&#160;and an array of strings&#160;words&#160;of&#160;the same length. Return&#160;all starting indices of substring(s) in&#160;s&#160;that is a concatenation of each word in&#160;words&#160;exactly once,&#160;in&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words-2/">花花酱 LeetCode 30. Substring with Concatenation of All Words</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a string&nbsp;<code>s</code>&nbsp;and an array of strings&nbsp;<code>words</code>&nbsp;of&nbsp;<strong>the same length</strong>. Return&nbsp;all starting indices of substring(s) in&nbsp;<code>s</code>&nbsp;that is a concatenation of each word in&nbsp;<code>words</code>&nbsp;<strong>exactly once</strong>,&nbsp;<strong>in any order</strong>,&nbsp;and&nbsp;<strong>without any intervening characters</strong>.</p>



<p>You can return the answer in&nbsp;<strong>any order</strong>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "barfoothefoobarman", words = ["foo","bar"]
<strong>Output:</strong> [0,9]
<strong>Explanation:</strong> Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
<strong>Output:</strong> []
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
<strong>Output:</strong> [6,9,12]
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li><li><code>s</code>&nbsp;consists of lower-case English letters.</li><li><code>1 &lt;= words.length &lt;= 5000</code></li><li><code>1 &lt;= words[i].length &lt;= 30</code></li><li><code>words[i]</code>&nbsp;consists of lower-case English letters.</li></ul>



<h2><strong>Solution: Hashtable + Brute Force</strong></h2>



<p>Try every index and use a hashtable to check coverage.</p>



<p>Time complexity: O(n*m*l)<br>Space complexity: O(m*l)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; findSubstring(string_view s, vector&lt;string&gt;&amp; words) {
    const int n = s.length();
    const int m = words.size();
    const int l = words[0].size();
    if (m * l &gt; n) return {};
    unordered_map&lt;string_view, int&gt; freq;
    for (const string&amp; word : words) ++freq[word];
    
    vector&lt;int&gt; ans;
    for (int i = 0; i &lt;= n - m * l; ++i) {
      unordered_map&lt;string_view, int&gt; seen;
      int count = 0;
      for (int k = 0; k &lt; m; ++k) {
        string_view t = s.substr(i + k * l, l);
        auto it = freq.find(t);
        if (it == end(freq)) break;
        if (++seen[t] &gt; it-&gt;second) break;
        ++count;  
      }
      if (count == m) ans.push_back(i);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words-2/">花花酱 LeetCode 30. Substring with Concatenation of All Words</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1668. Maximum Repeating Substring</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1668-maximum-repeating-substring/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1668-maximum-repeating-substring/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 28 Nov 2020 18:22:33 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7718</guid>

					<description><![CDATA[<p>For a string&#160;sequence, a string&#160;word&#160;is&#160;k-repeating&#160;if&#160;word&#160;concatenated&#160;k&#160;times is a substring of&#160;sequence. The&#160;word&#8216;s&#160;maximum&#160;k-repeating value&#160;is the highest value&#160;k&#160;where&#160;word&#160;is&#160;k-repeating in&#160;sequence. If&#160;word&#160;is not a substring of&#160;sequence,&#160;word&#8216;s maximum&#160;k-repeating value is&#160;0. Given strings&#160;sequence&#160;and&#160;word,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1668-maximum-repeating-substring/">花花酱 LeetCode 1668. Maximum Repeating Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>For a string&nbsp;<code>sequence</code>, a string&nbsp;<code>word</code>&nbsp;is&nbsp;<strong><code>k</code>-repeating</strong>&nbsp;if&nbsp;<code>word</code>&nbsp;concatenated&nbsp;<code>k</code>&nbsp;times is a substring of&nbsp;<code>sequence</code>. The&nbsp;<code>word</code>&#8216;s&nbsp;<strong>maximum&nbsp;<code>k</code>-repeating value</strong>&nbsp;is the highest value&nbsp;<code>k</code>&nbsp;where&nbsp;<code>word</code>&nbsp;is&nbsp;<code>k</code>-repeating in&nbsp;<code>sequence</code>. If&nbsp;<code>word</code>&nbsp;is not a substring of&nbsp;<code>sequence</code>,&nbsp;<code>word</code>&#8216;s maximum&nbsp;<code>k</code>-repeating value is&nbsp;<code>0</code>.</p>



<p>Given strings&nbsp;<code>sequence</code>&nbsp;and&nbsp;<code>word</code>, return&nbsp;<em>the&nbsp;<strong>maximum&nbsp;<code>k</code>-repeating value</strong>&nbsp;of&nbsp;<code>word</code>&nbsp;in&nbsp;<code>sequence</code></em>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sequence = "ababc", word = "ab"
<strong>Output:</strong> 2
<strong>Explanation: </strong>"abab" is a substring in "ababc".
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sequence = "ababc", word = "ba"
<strong>Output:</strong> 1
<strong>Explanation: </strong>"ba" is a substring in "ababc". "baba" is not a substring in "ababc".
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sequence = "ababc", word = "ac"
<strong>Output:</strong> 0
<strong>Explanation: </strong>"ac" is not a substring in "ababc". 
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= sequence.length &lt;= 100</code></li><li><code>1 &lt;= word.length &lt;= 100</code></li><li><code>sequence</code>&nbsp;and&nbsp;<code>word</code>&nbsp;contains only lowercase English letters.</li></ul>



<h2><strong>Solution: Brute Force</strong></h2>



<p>Time complexity: O(n^2)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution {
public:
  int maxRepeating(string sequence, string word) {
    string s(word);
    for (int i = 1;;++i) {
      if (sequence.find(s) == string::npos) return i - 1;
      s += word;
    }
    return -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1668-maximum-repeating-substring/">花花酱 LeetCode 1668. Maximum Repeating Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1668-maximum-repeating-substring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1520. Maximum Number of Non-Overlapping Substrings</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 19 Jul 2020 07:12:08 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[non-overlapping]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7122</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;of lowercase letters, you need to find the maximum number of&#160;non-empty&#160;substrings of&#160;s&#160;that meet the following conditions: The substrings do not overlap, that is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/">花花酱 LeetCode 1520. Maximum Number of Non-Overlapping Substrings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1520. Maximum Number of Non-Overlapping Substrings - 刷题找工作 EP344" width="500" height="281" src="https://www.youtube.com/embed/yAeI2uo3GP8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given a string&nbsp;<code>s</code>&nbsp;of lowercase letters, you need to find the maximum number of&nbsp;<strong>non-empty</strong>&nbsp;substrings of&nbsp;<code>s</code>&nbsp;that meet the following conditions:</p>



<ol><li>The substrings do not overlap, that is for any two substrings&nbsp;<code>s[i..j]</code>&nbsp;and&nbsp;<code>s[k..l]</code>, either&nbsp;<code>j &lt; k</code>&nbsp;or&nbsp;<code>i &gt; l</code>&nbsp;is true.</li><li>A substring that contains a certain character&nbsp;<code>c</code>&nbsp;must also contain all occurrences of&nbsp;<code>c</code>.</li></ol>



<p>Find&nbsp;<em>the maximum number of substrings that meet the above conditions</em>. If there are multiple solutions with the same number of substrings,&nbsp;<em>return the one with minimum total length.&nbsp;</em>It can be shown that there exists a unique solution of minimum total length.</p>



<p>Notice that you can return the substrings in&nbsp;<strong>any</strong>&nbsp;order.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "adefaddaccc"
<strong>Output:</strong> ["e","f","ccc"]
<strong>Explanation:</strong>&nbsp;The following are all the possible substrings that meet the conditions:
[
&nbsp; "adefaddaccc"
&nbsp; "adefadda",
&nbsp; "ef",
&nbsp; "e",
  "f",
&nbsp; "ccc",
]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abbaccd"
<strong>Output:</strong> ["d","bb","cc"]
<strong>Explanation: </strong>Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= s.length &lt;= 10^5</code></li><li><code>s</code>&nbsp;contains only lowercase English letters.</li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Observation: If a valid substring contains shorter valid strings, ignore the longer one and use the shorter one.<br>e.g. &#8220;abbeefba&#8221; is a valid substring, however, it includes &#8220;bbeefb&#8221;, &#8220;ee&#8221;, &#8220;f&#8221; three valid substrings, thus it won&#8217;t be part of the optimal solution, since we can always choose a shorter one, with potential to have one or more non-overlapping substrings. For &#8220;bbeefb&#8221;, again it includes &#8220;ee&#8221; and &#8220;f&#8221;, so it won&#8217;t be optimal either. Thus, the optimal ones are &#8220;ee&#8221; and &#8220;f&#8221;.</p>



<ol><li>We just need to record the first and last occurrence of each character</li><li>When we meet a character for the first time we must include everything from current pos to it&#8217;s last position. e.g. &#8220;<strong>a</strong>bbeefb<strong>a</strong>&#8221; | ccc, from first &#8216;a&#8217; to last &#8216;a&#8217;, we need to cover &#8220;abbeefba&#8221;</li><li>If any character in that range has larger end position, we must extend the string. e.g. &#8220;<strong>a</strong>bc<strong>a</strong>bbcc&#8221; | efg, from first &#8216;a&#8217; to last &#8216;a&#8217;, we have characters &#8216;b&#8217; and &#8216;c&#8217;, so we have to extend the string to cover all &#8216;b&#8217;s and &#8216;c&#8217;s. Our first valid substring extended from &#8220;abca&#8221; to &#8220;abcabbcc&#8221;.</li><li>If any character in the covered range has a smallest first occurrence, then it&#8217;s an invalid substring. e.g. ab | &#8220;cbc&#8221;, from first &#8216;c&#8217; to last &#8216;c&#8217;, we have &#8216;b&#8217;, but &#8216;b&#8217; is not fully covered, thus &#8220;cbc&#8221; is an invalid substring.</li><li>For the first valid substring, we append it to the ans array. &#8220;abbeefba&#8221; =&gt; ans = [&#8220;abbeefba&#8221;]</li><li>If we find a shorter substring that is full covered by the previous valid substring, we replace that substring with the shorter one. e.g.<br>&#8220;abbeefba&#8221; | ccc =&gt; ans = [&#8220;abbeefba&#8221;]<br>&#8220;<span style="text-decoration: underline;">a<strong>bbeefb</strong>a</span>&#8221; | ccc =&gt; ans = [&#8220;bbeefb&#8221;]<br>&#8220;a<span style="text-decoration: underline;">bb<strong>ee</strong>fb</span>a&#8221; | ccc =&gt; ans = [&#8220;ee&#8221;]</li><li>If the current substring does not overlap with previous one, append it to ans array.<br>&#8220;abb<strong>ee</strong>fba&#8221; | ccc =&gt; ans = [&#8220;ee&#8221;]<br>&#8220;abbee<strong>f</strong>ba&#8221; | ccc =&gt; ans = [&#8220;ee&#8221;, &#8220;f&#8221;]<br>&#8220;abbeefba<strong>ccc</strong>&#8221; =&gt; ans = [&#8220;ee&#8221;, &#8220;f&#8221;, &#8220;ccc&#8221;]</li></ol>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;string&gt; maxNumOfSubstrings(const string&amp; s) {
    const int n = s.length();    
    vector&lt;int&gt; l(26, INT_MAX);
    vector&lt;int&gt; r(26, INT_MIN);
    for (int i = 0; i &lt; n; ++i) {
      l[s[i] - 'a'] = min(l[s[i] - 'a'], i);
      r[s[i] - 'a'] = max(r[s[i] - 'a'], i);
    }
    auto extend = [&amp;](int i) -&gt; int {      
      int p = r[s[i] - 'a'];
      for (int j = i; j &lt;= p; ++j) {
        if (l[s[j] - 'a'] &lt; i) // invalid substring
          return -1; // e.g. a|&quot;ba&quot;...b
        p = max(p, r[s[j] - 'a']);
      }
      return p;
    };
    
    vector&lt;string&gt; ans;
    int last = -1;
    for (int i = 0; i &lt; n; ++i) {
      if (i != l[s[i] - 'a']) continue;
      int p = extend(i);
      if (p == -1) continue;
      if (i &gt; last) ans.push_back(&quot;&quot;);
      ans.back() = s.substr(i, p - i + 1);
      last = p;      
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/">花花酱 LeetCode 1520. Maximum Number of Non-Overlapping Substrings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1461. Check If a String Contains All Binary Codes of Size K</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1461-check-if-a-string-contains-all-binary-codes-of-size-k/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1461-check-if-a-string-contains-all-binary-codes-of-size-k/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 30 May 2020 23:26:06 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6836</guid>

					<description><![CDATA[<p>Given a binary string&#160;s&#160;and an integer&#160;k. Return&#160;True&#160;if any binary code of length&#160;k&#160;is a substring of&#160;s. Otherwise, return&#160;False. Example 1: Input: s = "00110110", k =&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1461-check-if-a-string-contains-all-binary-codes-of-size-k/">花花酱 LeetCode 1461. Check If a String Contains All Binary Codes of Size K</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a binary string&nbsp;<code>s</code>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>Return&nbsp;<em>True</em>&nbsp;if any binary code of length&nbsp;<code>k</code>&nbsp;is a substring of&nbsp;<code>s</code>. Otherwise, return&nbsp;<em>False</em>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "00110110", k = 2
<strong>Output:</strong> true
<strong>Explanation:</strong> The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indicies 0, 1, 3 and 2 respectively.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "00110", k = 2
<strong>Output:</strong> true
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "0110", k = 1
<strong>Output:</strong> true
<strong>Explanation:</strong> The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring. 
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "0110", k = 2
<strong>Output:</strong> false
<strong>Explanation:</strong> The binary code "00" is of length 2 and doesn't exist in the array.
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "0000000001011100", k = 4
<strong>Output:</strong> false
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= s.length &lt;= 5 * 10^5</code></li><li><code>s</code>&nbsp;consists of 0&#8217;s and 1&#8217;s only.</li><li><code>1 &lt;= k &lt;= 20</code></li></ul>



<h2><strong>Solution: Hashtable</strong></h2>



<p>Insert all possible substrings into a hashtable, the size of the hashtable should be 2^k.</p>



<p>Time complexity: O(n*k)<br>Space complexity: O(2^k*k) -&gt; O(2^k)</p>



<p>std::string_view: 484 ms, 40.1MB<br>std::string 644 ms, 58.6MB</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
// std::string_view: 468 ms, 37.3MB
// std::string:      636 ms, 58.6MB
class Solution {
public:
  bool hasAllCodes(string_view s, int k) {
    const int n = s.length();
    if ((n - k + 1) * k &lt; (1 &lt;&lt; k)) return false;
    unordered_set&lt;string_view&gt; c;
    for (int i = 0; i + k &lt;= n; ++i)
      c.insert(s.substr(i, k));    
    return c.size() == (1 &lt;&lt; k);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1461-check-if-a-string-contains-all-binary-codes-of-size-k/">花花酱 LeetCode 1461. Check If a String Contains All Binary Codes of Size K</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1461-check-if-a-string-contains-all-binary-codes-of-size-k/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 87. Scramble String</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-87-scramble-string/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-87-scramble-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 14 Mar 2020 18:14:40 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6481</guid>

					<description><![CDATA[<p>Given a string&#160;s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of&#160;s1&#160;=&#160;"great":&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-87-scramble-string/">花花酱 LeetCode 87. Scramble String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 87. Scramble String - 刷题找工作 EP314" width="500" height="375" src="https://www.youtube.com/embed/sETxfdHwxc0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given a string&nbsp;<em>s1</em>, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.</p>



<p>Below is one possible representation of&nbsp;<em>s1</em>&nbsp;=&nbsp;<code>"great"</code>:</p>



<pre class="wp-block-preformatted;crayon:false">    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t
</pre>



<p>To scramble the string, we may choose any non-leaf node and swap its two children.</p>



<p>For example, if we choose the node&nbsp;<code>"gr"</code>&nbsp;and swap its two children, it produces a scrambled string&nbsp;<code>"rgeat"</code>.</p>



<pre class="wp-block-preformatted;crayon:false">    rgeat
   /    \
  rg    eat
 / \    /  \
r   g  e   at
           / \
          a   t
</pre>



<p>We say that&nbsp;<code>"rgeat"</code>&nbsp;is a scrambled string of&nbsp;<code>"great"</code>.</p>



<p>Similarly, if we continue to swap the children of nodes&nbsp;<code>"eat"</code>&nbsp;and&nbsp;<code>"at"</code>, it produces a scrambled string&nbsp;<code>"rgtae"</code>.</p>



<pre class="wp-block-preformatted;crayon:false">    rgtae
   /    \
  rg    tae
 / \    /  \
r   g  ta  e
       / \
      t   a
</pre>



<p>We say that&nbsp;<code>"rgtae"</code>&nbsp;is a scrambled string of&nbsp;<code>"great"</code>.</p>



<p>Given two strings&nbsp;<em>s1</em>&nbsp;and&nbsp;<em>s2</em>&nbsp;of the same length, determine if&nbsp;<em>s2</em>&nbsp;is a scrambled string of&nbsp;<em>s1</em>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s1 = "great", s2 = "rgeat"
<strong>Output:</strong> true
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s1 = "abcde", s2 = "caebd"
<strong>Output:</strong> false</pre>



<h2><strong>Solution: Recursion</strong></h2>



<p>isScramble(s1, s2)<br>if s1 == s2: return true<br>if sorted(s1) != sroted(s2): return false<br>We try all possible partitions: </p>



<ol><li>s1[0:l] v.s s2[0:l] &amp;&amp; s1[l:] vs s2[l:]</li><li>s1[0:l] vs s2[L-l:l] &amp;&amp; s1[l:] vs s2[0:L-l]</li></ol>



<p>Time complexity: O(n^5)<br>Space complexity: O(n^4)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution {
public:
  bool isScramble(string_view s1, string_view s2) {    
    const int l = s1.length();        
    if (s1 == s2) return true;
    if (freq(s1) != freq(s2)) return false;
    for (int i = 1; i &lt; l; ++i)
      if (isScramble(s1.substr(0, i), s2.substr(0, i)) 
          &amp;&amp; isScramble(s1.substr(i), s2.substr(i)) 
          || isScramble(s1.substr(0, i), s2.substr(l - i, i))
          &amp;&amp; isScramble(s1.substr(i), s2.substr(0, l - i)))
        return true;
    return false;
  }
private:
  vector&lt;int&gt; freq(string_view s) {
    vector&lt;int&gt; f(26);
    for (char c : s) ++f[c - 'a'];
    return f;
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution: 
  @lru_cache(maxsize=None) # optional
  def isScramble(self, s1: str, s2: str) -&amp;gt; bool:
    if s1 == s2: return True
    # important, TLE if commneted out
    if Counter(s1) != Counter(s2): return False
    L = len(s1)
    for l in range(1, L):
      if self.isScramble(s1[0:l], s2[0:l]) and self.isScramble(s1[l:], s2[l:]): 
        return True
      if self.isScramble(s1[0:l], s2[L-l:]) and self.isScramble(s1[l:], s2[0:L-l]): 
        return True
    return False</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-87-scramble-string/">花花酱 LeetCode 87. Scramble String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-87-scramble-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1371. Find the Longest Substring Containing Vowels in Even Counts</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1371-find-the-longest-substring-containing-vowels-in-even-counts/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1371-find-the-longest-substring-containing-vowels-in-even-counts/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Mar 2020 08:00:30 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6400</guid>

					<description><![CDATA[<p>Given the string&#160;s, return the size of the longest substring containing each vowel an even number of times. That is, &#8216;a&#8217;, &#8216;e&#8217;, &#8216;i&#8217;, &#8216;o&#8217;, and&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1371-find-the-longest-substring-containing-vowels-in-even-counts/">花花酱 LeetCode 1371. Find the Longest Substring Containing Vowels in Even Counts</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1371. Find the Longest Substring Containing Vowels in Even Counts - 刷题找工作 EP312" width="500" height="375" src="https://www.youtube.com/embed/tAlQxFvak2U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given the string&nbsp;<code>s</code>, return the size of the longest substring containing each vowel an even number of times. That is, &#8216;a&#8217;, &#8216;e&#8217;, &#8216;i&#8217;, &#8216;o&#8217;, and &#8216;u&#8217; must appear an even number of times.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "eleetminicoworoep"
<strong>Output:</strong> 13
<strong>Explanation: </strong>The longest substring is "leetminicowor" which contains two each of the vowels: <strong>e</strong>, <strong>i</strong> and <strong>o</strong> and zero of the vowels: <strong>a</strong> and <strong>u</strong>.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leetcodeisgreat"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The longest substring is "leetc" which contains two e's.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "bcbcbc"
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this case, the given string "bcbcbc" is the longest because all vowels: <strong>a</strong>, <strong>e</strong>, <strong>i</strong>, <strong>o</strong> and <strong>u</strong> appear zero times.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= s.length &lt;= 5 x 10^5</code></li><li><code>s</code>&nbsp;contains only lowercase English letters.</li></ul>



<h2><strong>Solution: HashTable</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/03/1371-ep312.png" alt="" class="wp-image-6460" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/03/1371-ep312.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/03/1371-ep312-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/03/1371-ep312-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Record the first index when a state occurs. index &#8211; last_index is the length of the all-even-vowel substring.</p>



<p>State: {a: odd|even,  e: odd|even, &#8230;, u:odd|even}. </p>



<p>There are total 2^5 = 32 states that can be represented as a binary string.</p>



<p>whenever a vowel occurs, we flip the bit, e.g. odd-&gt;even, even-&gt;odd using XOR.</p>



<p>Time complexity: O(5*n)<br>Space complexity: O(32)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int findTheLongestSubstring(string s) {
    const char vowels[] = &quot;aeiou&quot;;
    vector&lt;int&gt; idx(1 &lt;&lt; 5, INT_MAX); // state -&gt; first_index    
    idx[0] = -1;
    int state = 0;
    int ans = 0;
    for (int i = 0; i &lt; s.length(); ++i) {
      for (int j = 0; j &lt; 5; ++j)
        if (s[i] == vowels[j]) state ^= 1 &lt;&lt; j;
      if (idx[state] == INT_MAX) idx[state] = i;
      ans = max(ans, i - idx[state]);
    }
    return ans;
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def findTheLongestSubstring(self, s: str) -&gt; int:
    idx = {0 : -1}
    vowels = &quot;aeiou&quot;
    state = 0
    ans = 0
    for i in range(len(s)):
      j = vowels.find(s[i])
      if j &gt;= 0: state ^= 1 &lt;&lt; j
      if state not in idx:
        idx[state] = i
      ans = max(ans, i - idx[state])
    return ans</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1371-find-the-longest-substring-containing-vowels-in-even-counts/">花花酱 LeetCode 1371. Find the Longest Substring Containing Vowels in Even Counts</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1371-find-the-longest-substring-containing-vowels-in-even-counts/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 1358. Number of Substrings Containing All Three Characters</title>
		<link>https://zxi.mytechroad.com/blog/string/1358-number-of-substrings-containing-all-three-characters/</link>
					<comments>https://zxi.mytechroad.com/blog/string/1358-number-of-substrings-containing-all-three-characters/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 23 Feb 2020 07:41:07 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6360</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;consisting only of characters&#160;a,&#160;b&#160;and&#160;c. Return the number of substrings containing&#160;at least&#160;one occurrence of all these characters&#160;a,&#160;b&#160;and&#160;c. Example 1: Input: s = "abcabc" Output:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/1358-number-of-substrings-containing-all-three-characters/">花花酱 1358. Number of Substrings Containing All Three Characters</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a string&nbsp;<code>s</code>&nbsp;consisting only of characters&nbsp;<em>a</em>,&nbsp;<em>b</em>&nbsp;and&nbsp;<em>c</em>.</p>



<p>Return the number of substrings containing&nbsp;<strong>at least</strong>&nbsp;one occurrence of all these characters&nbsp;<em>a</em>,&nbsp;<em>b</em>&nbsp;and&nbsp;<em>c</em>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abcabc"
<strong>Output:</strong> 10
<strong>Explanation:</strong> The substrings containing&nbsp;at least&nbsp;one occurrence of the characters&nbsp;<em>a</em>,&nbsp;<em>b</em>&nbsp;and&nbsp;<em>c are "</em>abc<em>", "</em>abca<em>", "</em>abcab<em>", "</em>abcabc<em>", "</em>bca<em>", "</em>bcab<em>", "</em>bcabc<em>", "</em>cab<em>", "</em>cabc<em>" </em>and<em> "</em>abc<em>" </em>(<strong>again</strong>)<em>. </em>
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aaacb"
<strong>Output:</strong> 3
<strong>Explanation:</strong> The substrings containing&nbsp;at least&nbsp;one occurrence of the characters&nbsp;<em>a</em>,&nbsp;<em>b</em>&nbsp;and&nbsp;<em>c are "</em>aaacb<em>", "</em>aacb<em>" </em>and<em> "</em>acb<em>".</em>
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abc"
<strong>Output:</strong> 1
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>3 &lt;= s.length &lt;= 5 x 10^4</code></li><li><code>s</code>&nbsp;only consists of&nbsp;<em>a</em>,&nbsp;<em>b</em>&nbsp;or&nbsp;<em>c&nbsp;</em>characters.</li></ul>



<h2><strong>Solution</strong></h2>



<p>Record the last index of each character. </p>



<p>At each index i, we can choose any index j that j &lt;= min(last_a, last_b, last_c) as the starting point, and there will be  min(last_a, last_b, last_c) + 1 valid substrings.</p>



<p>e.g. aabbabcc&#8230;<br>last_a = 4<br>last_b = 5<br>last_c = 7<br>min(last_a, last_b, last_c) = 4<br>aabba | bcc<br>We can choose any char with index &lt;= 4 as string point, there are 5 of them:<br>aabbabcc<br>abbabcc<br>bbabcc<br>babcc<br>abcc</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int numberOfSubstrings(string s) {
    vector&lt;int&gt; l{-1,-1,-1};
    int ans = 0;
    for (size_t i = 0; i &lt; s.length(); ++i) {
      l[s[i] - 'a'] = i;
      ans += 1 + *min_element(begin(l), end(l));
    }
    return ans;
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def numberOfSubstrings(self, s: str) -&gt; int:
    l = {'a':-1, 'b':-1, 'c':-1}
    ans = 0
    for i, ch in enumerate(s):
      l[ch] = i
      ans += min(l.values()) + 1
    return ans</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/1358-number-of-substrings-containing-all-three-characters/">花花酱 1358. Number of Substrings Containing All Three Characters</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/1358-number-of-substrings-containing-all-three-characters/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1156. Swap For Longest Repeated Character Substring</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1156-swap-for-longest-repeated-character-substring/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1156-swap-for-longest-repeated-character-substring/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Aug 2019 21:56:58 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5426</guid>

					<description><![CDATA[<p>Given a string&#160;text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1156-swap-for-longest-repeated-character-substring/">花花酱 LeetCode 1156. Swap For Longest Repeated Character Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a string&nbsp;<code>text</code>, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> text = "ababa"
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> text = "aaabaaa"
<strong>Output:</strong> 6
<strong>Explanation:</strong> Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> text = "aaabbaaa"
<strong>Output:</strong> 4
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> text = "aaaaa"
<strong>Output:</strong> 5
<strong>Explanation:</strong> No need to swap, longest repeated character substring is "aaaaa", length is 5.
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> text = "abcdef"
<strong>Output:</strong> 1
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= text.length &lt;= 20000</code></li><li><code>text</code>&nbsp;consist of lowercase English characters only.</li></ul>



<h2><strong>Solution: HashTable</strong></h2>



<p>Pre-processing</p>



<ol><li>Compute the longest repeated substring starts and ends with text[i].</li><li>Count the frequency of each letter.</li></ol>



<p>Main</p>



<ol><li>Loop through each letter</li><li>Check the left and right letter<ul><li>if they are the same, len = left + right<ul><li>e.g1. &#8220;aa c aaa [b] aaaa&#8221; =&gt; len = 3 + 4 = 7</li></ul></li><li>if they are not the same, len = max(left, right)  <ul><li>e.g2. &#8220;aa [b] ccc d c&#8221;  =&gt; len = max(2, 3) = 3</li></ul></li></ul></li><li>If the letter occurs more than len times, we can always find an extra one and swap it with the current letter =&gt; ++len<ul><li>e.g.1, count[&#8220;a&#8221;] = 9 &gt; 7, len = 7 + 1 = 8</li><li>e.g.2, count[&#8220;c&#8221;] = 4 &gt; 3, len = 3 + 1 = 4</li></ul></li></ol>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxRepOpt1(string text) {
    int n = text.length();
    // Length of repeted substring ends with text[i]
    vector&lt;vector&lt;int&gt;&gt; len1(n, vector&lt;int&gt;(26));
    // Length of repeated substring starts with text[i]
    vector&lt;vector&lt;int&gt;&gt; len2(n, vector&lt;int&gt;(26));
    vector&lt;int&gt; counts(26);
    int last = -1; // not a letter
    int l = 0;
    int ans = 0;
    for (int i = 0; i &lt; n; ++i) {
      const int c = text[i] - 'a';
      if (c == last) {
        ++l;
      } else { 
        last = c;
        l = 1;
      }      
      len1[i][c] = l;
      len2[i - l + 1][c] = l;
      ++counts[c];
      ans = max(ans, l);
    }
    
    for (int i = 1; i &lt; n - 1; ++i) {
      int cl = text[i - 1] - 'a';
      int cr = text[i + 1] - 'a';
      int left = len1[i - 1][cl];
      int right = len2[i + 1][cr];
      int count = 0;      
      if (cl != cr) {
        // e.g. &quot;c aaa b cccc&quot; =&gt; &quot;b aaa ccccc&quot;
        count = max(left + (counts[cl] &gt; left ? 1 : 0), 
                    right + (counts[cr] &gt; right ? 1 : 0));
      } else {
        // e.g. &quot;a c aaa b aaaa&quot; =&gt; &quot;b c aaaaaaaa&quot;
        count = left + right;
        if (counts[cl] &gt; count) ++count;
      }
      ans = max(ans, count);
    }
    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1156-swap-for-longest-repeated-character-substring/">花花酱 LeetCode 1156. Swap For Longest Repeated Character Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1156-swap-for-longest-repeated-character-substring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 30. Substring with Concatenation of All Words</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 02 Mar 2019 16:03:46 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4914</guid>

					<description><![CDATA[<p>You are given a string,&#160;s, and a list of words,&#160;words, that are all of the same length. Find all starting indices of substring(s) in&#160;sthat is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words/">花花酱 LeetCode 30. Substring with Concatenation of All Words</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a string,&nbsp;<strong>s</strong>, and a list of words,&nbsp;<strong>words</strong>, that are all of the same length. Find all starting indices of substring(s) in&nbsp;<strong>s</strong>that is a concatenation of each word in&nbsp;<strong>words</strong>&nbsp;exactly once and without any intervening characters.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted crayon:false"><strong>Input:
  s =</strong> "barfoothefoobarman",
<strong>  words = </strong>["foo","bar"]
<strong>Output:</strong> <code>[0,9]</code>
<strong>Explanation:</strong> Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted crayon:false"><strong>Input:
  s =</strong> "wordgoodgoodgoodbestword",
<strong>  words = </strong>["word","good","best","word"]
<strong>Output:</strong> <code>[]</code></pre>



<h2><strong>Solution1: HashTable + Brute Force</strong></h2>



<p>Time complexity: O((|S| &#8211; |W|*l) * |W|*l))<br>Space complexity: O(|W|*l)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
// std::string_view running time: 128 ms, 16 MB
// std::string running time: 156 ms, 22.4 MB
class Solution {
public:
  vector&lt;int&gt; findSubstring(string s, vector&lt;string&gt;&amp; words) {
    if (words.empty() || s.empty()) return {};
    
    const int n = words.size();
    const int l = words[0].length();
    
    if (n * l &gt; s.length()) return {};
    
    std::string_view ss(s);
    
    std::unordered_map&lt;std::string_view, int&gt; expected;
    
    for (const string&amp; word : words)
      ++expected[string_view(word)];

    vector&lt;int&gt; ans;
    
    for (int i = 0; i &lt;= ss.length() - n * l; ++i) {      
      std::unordered_map&lt;std::string_view, int&gt; seen;
      int count = 0;
      for (int j = 0; j &lt; n; ++j) {
        std::string_view w = ss.substr(i + j * l, l);
        auto it = expected.find(w);
        if (it == expected.end()) break;
        if (++seen[w] &gt; it-&gt;second) break;
        ++count;
      }
      if (count == n) 
        ans.push_back(i);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words/">花花酱 LeetCode 30. Substring with Concatenation of All Words</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-30-substring-with-concatenation-of-all-words/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 937. Reorder Log Files</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-937-reorder-log-files/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-937-reorder-log-files/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Nov 2018 07:33:06 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[partition]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4280</guid>

					<description><![CDATA[<p>Problem https://leetcode.com/problems/reorder-log-files/description/ You have an array of logs.  Each log is a space delimited string of words. For each log, the first word in each log&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-937-reorder-log-files/">花花酱 LeetCode 937. Reorder Log Files</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p><a href="https://leetcode.com/problems/reorder-log-files/description/">https://leetcode.com/problems/reorder-log-files/description/</a></p>
<p>You have an array of <code>logs</code>.  Each log is a space delimited string of words.</p>
<p>For each log, the first word in each log is an alphanumeric <em>identifier</em>.  Then, either:</p>
<ul>
<li>Each word after the identifier will consist only of lowercase letters, or;</li>
<li>Each word after the identifier will consist only of digits.</li>
</ul>
<p>We will call these two varieties of logs <em>letter-logs</em> and <em>digit-logs</em>.  It is guaranteed that each log has at least one word after its identifier.</p>
<p>Reorder the logs so that all of the letter-logs come before any digit-log.  The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties.  The digit-logs should be put in their original order.</p>
<p>Return the final order of the logs.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]</span>
<strong>Output: </strong><span id="example-output-1">["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>0 &lt;= logs.length &lt;= 100</code></li>
<li><code>3 &lt;= logs[i].length &lt;= 100</code></li>
<li><code>logs[i]</code> is guaranteed to have an identifier, and a word after the identifier.</li>
</ol>
<h1><strong>Solution: Partition + Sort</strong></h1>
<ol>
<li>partition the array such that all digit logs are after all letter logs</li>
<li>sort the letter logs part based on the log content</li>
</ol>
<p>Time complexity: O(n + aloga)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution {
public:
    vector&lt;string&gt; reorderLogFiles(vector&lt;string&gt;&amp; logs) {
      auto alpha_end = std::stable_partition(begin(logs),  end(logs), 
        [](const string&amp; log){ return isalpha(log.back()); });
      std::sort(begin(logs), alpha_end, [](const string&amp; a, const string&amp; b){
        return a.substr(a.find(' ')) &lt; b.substr(b.find(' '));
      });
      return logs;
    }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-937-reorder-log-files/">花花酱 LeetCode 937. Reorder Log Files</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-937-reorder-log-files/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 28. Implement strStr()</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-28-implement-strstr/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-28-implement-strstr/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Oct 2018 19:41:33 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4138</guid>

					<description><![CDATA[<p>Problem Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack =&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-28-implement-strstr/">花花酱 LeetCode 28. Implement strStr()</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Implement <a href="http://www.cplusplus.com/reference/cstring/strstr/" target="_blank" rel="noopener">strStr()</a>.</p>
<p>Return the index of the first occurrence of needle in haystack, or <strong>-1</strong> if needle is not part of haystack.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> haystack = "hello", needle = "ll"
<strong>Output:</strong> 2
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> haystack = "aaaaa", needle = "bba"
<strong>Output:</strong> -1
</pre>
<p><strong>Clarification:</strong></p>
<p>What should we return when <code>needle</code> is an empty string? This is a great question to ask during an interview.</p>
<p>For the purpose of this problem, we will return 0 when <code>needle</code> is an empty string. This is consistent to C&#8217;s <a href="http://www.cplusplus.com/reference/cstring/strstr/" target="_blank" rel="noopener">strstr()</a> and Java&#8217;s <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)" target="_blank" rel="noopener">indexOf()</a>.</p>
<h1><strong>Solution 1: Brute Force</strong></h1>
<p>Time complexity: O(mn)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 4 ms
class Solution {
public:
  int strStr(string haystack, string needle) {
    const int l1 = haystack.length();
    const int l2 = needle.length();
    for (int i = 0; i &lt;= l1 - l2; ++i) {
      int j = 0;
      while (j &lt; l2 &amp;&amp; haystack[i + j] == needle[j]) ++j;
      if (j == l2) return i;
    }
    return -1;
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def strStr(self, haystack, needle):
    l1 = len(haystack)
    l2 = len(needle)
    for i in range(l1 - l2 + 1):
      if haystack[i:i+l2] == needle: return i
    return -1</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-28-implement-strstr/">花花酱 LeetCode 28. Implement strStr()</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-28-implement-strstr/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 567. Permutation in String</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-567-permutation-in-string/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-567-permutation-in-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 29 Jun 2018 05:13:00 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[permuation]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2957</guid>

					<description><![CDATA[<p>Problem 题目大意：给你s1, s2，问你s2的子串中是否存在s1的一个排列。 https://leetcode.com/problems/permutation-in-string/description/ Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string&#8217;s&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-567-permutation-in-string/">花花酱 LeetCode 567. Permutation in String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/wpq03MmEHIM?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>题目大意：给你s1, s2，问你s2的子串中是否存在s1的一个排列。</p>
<p><a href="https://leetcode.com/problems/permutation-in-string/description/">https://leetcode.com/problems/permutation-in-string/description/</a></p>
<p>Given two strings <b>s1</b> and <b>s2</b>, write a function to return true if <b>s2</b> contains the permutation of <b>s1</b>. In other words, one of the first string&#8217;s permutations is the <b>substring</b> of the second string.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b>s1 = "ab" s2 = "eidbaooo"
<b>Output:</b>True
<b>Explanation:</b> s2 contains one permutation of s1 ("ba").
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b>s1= "ab" s2 = "eidboaoo"
<b>Output:</b> False
</pre>
<p><b>Note:</b></p>
<ol>
<li>The input strings only contain lower case letters.</li>
<li>The length of both given strings is in range [1, 10,000].</li>
</ol>
<p><img class="alignnone size-full wp-image-2962" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/567-ep200.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/567-ep200.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/567-ep200-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/567-ep200-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution: Sliding Window</strong></h1>
<p>Time Complexity: O(l1 + l2 * 26) = O(l1 + l2)</p>
<p>Space Complexity: O(26 * 2) = O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 12 ms
class Solution {
public:
  bool checkInclusion(string s1, string s2) {
    int l1 = s1.length();
    int l2 = s2.length();    
    vector&lt;int&gt; c1(26);
    vector&lt;int&gt; c2(26);
    for (const char c : s1)
      ++c1[c - 'a'];
    for (int i = 0; i &lt; l2; ++i) {
      if (i &gt;= l1)
        --c2[s2[i - l1] - 'a'];
      ++c2[s2[i] - 'a'];      
      if (c1 == c2) return true;      
    }
    return false;
  }
};</pre><p></p>
<h1>Related Problems</h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/difficulty/hard/leetcode-480-sliding-window-median/">花花酱 LeetCode 480. Sliding Window Median</a></li>
<li><a href="http://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/">花花酱 LeetCode 239. Sliding Window Maximum</a></li>
<li><a href="http://zxi.mytechroad.com/blog/string/leetcode-438-find-all-anagrams-in-a-string/">花花酱 LeetCode 438. Find All Anagrams in a String</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-567-permutation-in-string/">花花酱 LeetCode 567. Permutation in String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-567-permutation-in-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
