<?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>String &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/string/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Thu, 17 Apr 2025 03:28:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>String &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 3517. Smallest Palindromic Rearrangement I</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-3517-smallest-palindromic-rearrangement-i/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-3517-smallest-palindromic-rearrangement-i/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 17 Apr 2025 03:19:33 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10364</guid>

					<description><![CDATA[这题考查的是排序吧&#8230; 还有rbegin的使用。 普通排序：时间 O(nlogn) / 空间 O(1) 前半部分顺序排序，后半部分逆序排序。 [crayon-6803ad96d63d1041661515/] 计数排序：时间：O(n)，空间：O(n) -> O(1) 首尾一起写 [crayon-6803ad96d63e2492246086/]]]></description>
										<content:encoded><![CDATA[
<p>这题考查的是排序吧&#8230; 还有rbegin的使用。</p>



<p>普通排序：时间 O(nlogn) / 空间 O(1)</p>



<p>前半部分顺序排序，后半部分逆序排序。</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  string smallestPalindrome(string s) {
    const int n = s.length();
    sort(begin(s), begin(s) + n / 2);
    sort(rbegin(s), rbegin(s) + n / 2);
    return s;
  }
};</pre>



<p>计数排序：时间：O(n)，空间：O(n) -> O(1)</p>



<p>首尾一起写</p>



<pre class="urvanov-syntax-highlighter-plain-tag">// 7 ms, 54.65MB
class Solution {
public:
  string smallestPalindrome(string s) {
    vector&lt;int&gt; f(128);
    for (size_t i = 0; i &lt; s.size() / 2; ++i)
      ++f[s[i]];
    auto h=begin(s);
    auto t=rbegin(s);
    for (char c = 'a'; c &lt;= 'z'; ++c)
      while (f[c]--)
        *h++ = *t++ = c;
    return s;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-3517-smallest-palindromic-rearrangement-i/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2023-number-of-pairs-of-strings-with-concatenation-equal-to-target/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2023-number-of-pairs-of-strings-with-concatenation-equal-to-target/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 11 Apr 2025 16:24:45 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[string_view]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10337</guid>

					<description><![CDATA[方法1: Brute Force 枚举所有的(nums[i], nums[j])组合，相加在和target比较。 时间复杂度：O(mn2) m为字符串的最长长度。空间复杂度：O(m) 优化前 67ms, 49.3M [crayon-6803ad96d6acd182346331/] 一些工程上的优化 优化后 3ms, 12.88MB [crayon-6803ad96d6ad9659287025/]]]></description>
										<content:encoded><![CDATA[
<p>方法1: Brute Force</p>



<p>枚举所有的(nums[i], nums[j])组合，相加在和target比较。</p>



<p>时间复杂度：O(mn<sup>2</sup>) m为字符串的最长长度。<br>空间复杂度：O(m)</p>



<p>优化前 67ms, 49.3M</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int numOfPairs(vector&lt;string&gt;&amp; nums, string target) {
    const int n = nums.size();
    int ans = 0;
    for (int i = 0; i &lt; n; ++i)
      for (int j = 0; j &lt; n; ++j)
        if (i != j &amp;&amp; nums[i] + nums[j] == target)
          ++ans;
    return ans;
  }
};</pre>



<p>一些工程上的优化</p>



<ul class="wp-block-list">
<li>用string_view作为参数类型，减少一次string copy</li>



<li>先比较长度，再判断内容。</li>



<li>string_view.substr 是O(1)时间，和直接用strncmp比较内容是一样的。</li>
</ul>



<p>优化后 3ms, 12.88MB</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int numOfPairs(vector&lt;string&gt;&amp; nums, string_view target) {
    const int n = nums.size();
    int ans = 0;
    for (int i = 0; i &lt; n; ++i)
      for (int j = 0; j &lt; n; ++j)
        if (i != j 
            &amp;&amp; nums[i].size() + nums[j].size() == target.size()
            &amp;&amp; target.substr(0, nums[i].size()) == nums[i]
            &amp;&amp; target.substr(nums[i].size()) == nums[j])
              ++ans;
    return ans;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2023-number-of-pairs-of-strings-with-concatenation-equal-to-target/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2296 Design a Text Editor</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 03 Apr 2025 04:08:43 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10252</guid>

					<description><![CDATA[方法1：双向链表来存储文本，迭代器指向光标所在的位置。加一个dummy head会使代码简单很多。 时间复杂度：TextEditor O(1) addText O(&#124;text&#124;) deleteText O(k) cursorLeft O(k) cursorRight(k)空间复杂度：O(n) 由于每个字符需要创建一个节点（17+个字节），虽然没有超时，但实际工程中是不能使用这种方式的。 [crayon-6803ad96d6d78504403215/] 方法2: 用两个string来代表光标左边的字符串和光标右边的字符串。注：右边字符串是反转的。 左右两边的字符串只会增长（或者覆盖），不会缩短，这是用空间换时间。 删除的时候就是修改了长度而已，并没有缩短字符串，所以是O(1)的。如果缩短的话需则要O(k)时间，还要加上内存释放/再分配的时间，应该会慢一些但不多。 移动光标的时候，就是把左边字符串的最后k个copy到右边的最后面，或者反过来。同样没有缩短，只会变长。 时间复杂度: TextEditor O(1) addText O(&#124;text&#124;) deleteText O(1)&#8230;]]></description>
										<content:encoded><![CDATA[
<p>方法1：双向链表来存储文本，迭代器指向光标所在的位置。加一个dummy head会使代码简单很多。</p>



<p>时间复杂度：TextEditor O(1) addText O(|text|) deleteText O(k) cursorLeft O(k) cursorRight(k)<br>空间复杂度：O(n)</p>



<p>由于每个字符需要创建一个节点（17+个字节），虽然没有超时，但实际工程中是不能使用这种方式的。</p>



<pre class="urvanov-syntax-highlighter-plain-tag">// https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/
class TextEditor {
public:
  TextEditor(): data_{'$'}, cursor_{begin(data_)} {}
  
  void addText(string text) {
    for (char c : text)
      cursor_ = data_.insert(++cursor_, c);
  }
  
  int deleteText(int k) {
    for (int i = 0; i &lt; k; ++i) {
      if (cursor_ == begin(data_)) return i;
      data_.erase(cursor_--);
    }
    return k;
  }
  
  string cursorLeft(int k) {
    for (int i = 0; i &lt; k; ++i) {
      if (cursor_ == begin(data_)) break;
      cursor_--;
    }
    return getText();
  }
  
  string cursorRight(int k) {
    for (int i = 0; i &lt; k; ++i) {
      if (cursor_ == prev(end(data_))) break;
      cursor_++;
    }
    return getText();
  }
private:
  string getText() {
    string ans;
    auto it = cursor_;
    for (int i = 0; i &lt; 10; ++i) {
      if (it == begin(data_)) break;
      ans += *it--;
    }
    reverse(begin(ans), end(ans));
    return ans;
  }

  list&lt;char&gt; data_;
  list&lt;char&gt;::iterator cursor_;
};</pre>



<p>方法2: 用两个string来代表光标左边的字符串和光标右边的字符串。注：右边字符串是反转的。</p>



<p>左右两边的字符串只会增长（或者覆盖），不会缩短，这是用空间换时间。</p>



<p>删除的时候就是修改了长度而已，并没有缩短字符串，所以是O(1)的。<br>如果缩短的话需则要O(k)时间，还要加上内存释放/再分配的时间，应该会慢一些但不多。</p>



<p>移动光标的时候，就是把左边字符串的最后k个copy到右边的最后面，或者反过来。同样没有缩短，只会变长。</p>



<p>时间复杂度: TextEditor O(1) addText O(|text|) deleteText O(1) cursorLeft O(k) cursorRight(k)<br>空间复杂度：O(n)，n为构建的最长的字符串</p>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/Screenshot-2025-04-03-at-9.37.22 PM.png"><img fetchpriority="high" decoding="async" width="676" height="511" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/Screenshot-2025-04-03-at-9.37.22 PM.png" alt="" class="wp-image-10262" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/Screenshot-2025-04-03-at-9.37.22 PM.png 676w, https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/Screenshot-2025-04-03-at-9.37.22 PM-300x227.png 300w" sizes="(max-width: 676px) 100vw, 676px" /></a></figure>



<pre class="urvanov-syntax-highlighter-plain-tag">// https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/
class TextEditor {
public:
  TextEditor() {}
  
  void addText(string_view text) {
    ensureSize(l, m + text.size());
    copy(begin(text), end(text), begin(l) + m);
    m += text.size();
  }
  
  int deleteText(int k) {
    k = min(k, m);
    m -= k;
    return k;
  }
  
  string cursorLeft(int k) {
    ensureSize(r, n + k);
    for (k = min(k, m); k &gt; 0; --k)
      r[n++] = l[--m];
    return getText();
  }
  
  string cursorRight(int k) {
    ensureSize(l, m + k);
    for (k = min(k, n); k &gt; 0; --k)
      l[m++] = r[--n];
    return getText();
  }
private:
  inline void ensureSize(string&amp; s, int size) {
    if (s.size() &lt; size)
      s.resize(size);
  }

  string getText() const {
    return string(begin(l) + m - min(m, 10), begin(l) + m);
  }

  string l;
  string r;
  int m = 0;
  int n = 0;
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 3498 Reverse Degree of a String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-3498-reverse-degree-of-a-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-3498-reverse-degree-of-a-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 31 Mar 2025 04:15:09 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[ascii]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10247</guid>

					<description><![CDATA[送分题，简单仿真即可。 时间复杂度：O(n)空间复杂度：O(1) [crayon-6803ad96d71d3421061471/]]]></description>
										<content:encoded><![CDATA[
<p>送分题，简单仿真即可。</p>



<p>时间复杂度：O(n)<br>空间复杂度：O(1)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">// https://zxi.mytechroad.com/blog/string/leetcode-3498-reverse-degree-of-a-string/
class Solution {
public:
  int reverseDegree(string s) {
    int ans = 0;
    for (int i = 0; i &lt; s.size(); ++i)
      ans += ('z' - s[i] + 1) * (i + 1);
    return ans;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-3498-reverse-degree-of-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 3029. Minimum Time to Revert Word to Initial State I</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-3029-minimum-time-to-revert-word-to-initial-state-i/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-3029-minimum-time-to-revert-word-to-initial-state-i/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 06 Feb 2024 02:02:17 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[surffix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10114</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;string&#160;word&#160;and an integer&#160;k. At every second, you must perform the following operations: Remove the first&#160;k&#160;characters of&#160;word. Add any&#160;k&#160;characters to the end of&#160;word.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;string&nbsp;<code>word</code>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>At every second, you must perform the following operations:</p>



<ul class="wp-block-list"><li>Remove the first&nbsp;<code>k</code>&nbsp;characters of&nbsp;<code>word</code>.</li><li>Add any&nbsp;<code>k</code>&nbsp;characters to the end of&nbsp;<code>word</code>.</li></ul>



<p><strong>Note</strong>&nbsp;that you do not necessarily need to add the same characters that you removed. However, you must perform&nbsp;<strong>both</strong>&nbsp;operations at every second.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;time greater than zero required for</em>&nbsp;<code>word</code>&nbsp;<em>to revert to its&nbsp;<strong>initial</strong>&nbsp;state</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= word.length &lt;= 50</code></li><li><code>1 &lt;= k &lt;= word.length</code></li><li><code>word</code>&nbsp;consists only of lowercase English letters.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Suffix ==? Prefix</strong></h2>



<p>Compare the suffix with prefix.</p>



<p>word = &#8220;abacaba&#8221;, k = 3<br>ans = 1, &#8220;<s>aba</s>caba&#8221; != &#8220;abac<s>aba</s>&#8220;<br>ans = 2, &#8220;<s>abacab</s>a&#8221; == &#8220;a<s>bacaba</s>&#8220;, we find it.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int minimumTimeToInitialState(string_view word, int k) {
    const int n = word.length();
    for (int i = 1; i * k &lt; n; ++i) {
      string_view t = word.substr(i * k);
      if (t == word.substr(0, t.length())) return i;
    }      
    return (n + k - 1) / k;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-3029-minimum-time-to-revert-word-to-initial-state-i/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2828. Check if a String Is an Acronym of Words</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2828-check-if-a-string-is-an-acronym-of-words/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2828-check-if-a-string-is-an-acronym-of-words/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 26 Aug 2023 16:29:43 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10082</guid>

					<description><![CDATA[Given an array of strings&#160;words&#160;and a string&#160;s, determine if&#160;s&#160;is an&#160;acronym&#160;of words. The string&#160;s&#160;is considered an acronym of&#160;words&#160;if it can be formed by concatenating the&#160;first&#160;character of&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an array of strings&nbsp;<code>words</code>&nbsp;and a string&nbsp;<code>s</code>, determine if&nbsp;<code>s</code>&nbsp;is an&nbsp;<strong>acronym</strong>&nbsp;of words.</p>



<p>The string&nbsp;<code>s</code>&nbsp;is considered an acronym of&nbsp;<code>words</code>&nbsp;if it can be formed by concatenating the&nbsp;<strong>first</strong>&nbsp;character of each string in&nbsp;<code>words</code>&nbsp;<strong>in order</strong>. For example,&nbsp;<code>"ab"</code>&nbsp;can be formed from&nbsp;<code>["apple", "banana"]</code>, but it can&#8217;t be formed from&nbsp;<code>["bear", "aardvark"]</code>.</p>



<p>Return&nbsp;<code>true</code><em>&nbsp;if&nbsp;</em><code>s</code><em>&nbsp;is an acronym of&nbsp;</em><code>words</code><em>, and&nbsp;</em><code>false</code><em>&nbsp;otherwise.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["alice","bob","charlie"], s = "abc"
<strong>Output:</strong> true
<strong>Explanation:</strong> The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym. 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["an","apple"], s = "a"
<strong>Output:</strong> false
<strong>Explanation:</strong> The first character in the words "an" and "apple" are 'a' and 'a', respectively. 
The acronym formed by concatenating these characters is "aa". 
Hence, s = "a" is not the acronym.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["never","gonna","give","up","on","you"], s = "ngguoy"
<strong>Output:</strong> true
<strong>Explanation: </strong>By concatenating the first character of the words in the array, we get the string "ngguoy". 
Hence, s = "ngguoy" is the acronym.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= words.length &lt;= 100</code></li><li><code>1 &lt;= words[i].length &lt;= 10</code></li><li><code>1 &lt;= s.length &lt;= 100</code></li><li><code>words[i]</code>&nbsp;and&nbsp;<code>s</code>&nbsp;consist of lowercase English letters.<br></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Check the first letter of each word</strong></h2>



<p>No need to concatenate, just check the first letter of each word.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  bool isAcronym(vector&lt;string&gt;&amp; words, string_view s) {
    if (words.size() != s.size()) return false;
    for (int i = 0; i &lt; s.size(); ++i)
      if (words[i][0] != s[i]) return false;
    return true;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2828-check-if-a-string-is-an-acronym-of-words/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2586. Count the Number of Vowel Strings in Range</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2586-count-the-number-of-vowel-strings-in-range/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2586-count-the-number-of-vowel-strings-in-range/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Mar 2023 04:32:34 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[vowel]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9977</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;array of string&#160;words&#160;and two integers&#160;left&#160;and&#160;right. A string is called a&#160;vowel string&#160;if it starts with a vowel character and ends with a vowel&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;array of string&nbsp;<code>words</code>&nbsp;and two integers&nbsp;<code>left</code>&nbsp;and&nbsp;<code>right</code>.</p>



<p>A string is called a&nbsp;<strong>vowel string</strong>&nbsp;if it starts with a vowel character and ends with a vowel character where vowel characters are&nbsp;<code>'a'</code>,&nbsp;<code>'e'</code>,&nbsp;<code>'i'</code>,&nbsp;<code>'o'</code>, and&nbsp;<code>'u'</code>.</p>



<p>Return&nbsp;<em>the number of vowel strings&nbsp;</em><code>words[i]</code><em>&nbsp;where&nbsp;</em><code>i</code><em>&nbsp;belongs to the inclusive range&nbsp;</em><code>[left, right]</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["are","amy","u"], left = 0, right = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> 
- "are" is a vowel string because it starts with 'a' and ends with 'e'.
- "amy" is not a vowel string because it does not end with a vowel.
- "u" is a vowel string because it starts with 'u' and ends with 'u'.
The number of vowel strings in the mentioned range is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> 
- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.
- "mu" is not a vowel string because it does not start with a vowel.
- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.
- "artro" is a vowel string because it starts with 'a' and ends with 'o'.
The number of vowel strings in the mentioned range is 3.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= words.length &lt;= 1000</code></li><li><code>1 &lt;= words[i].length &lt;= 10</code></li><li><code>words[i]</code>&nbsp;consists of only lowercase English letters.</li><li><code>0 &lt;= left &lt;= right &lt; words.length</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution:</strong></h2>



<p>Iterator overs words, from left to right. Check the first and last element of the string.</p>



<p>Time complexity: O(|right &#8211; left + 1|)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int vowelStrings(vector&lt;string&gt;&amp; words, int left, int right) {
    auto isVowel = [](char c) {
      return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    };
    return count_if(begin(words) + left, begin(words) + right + 1, [&amp;](const string&amp; w) {
      return isVowel(w.front()) &amp;&amp; isVowel(w.back());
    });
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2586-count-the-number-of-vowel-strings-in-range/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2452. Words Within Two Edits of Dictionary</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2452-words-within-two-edits-of-dictionary%ef%bf%bc/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2452-words-within-two-edits-of-dictionary%ef%bf%bc/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 31 Oct 2022 17:25:21 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[edit distance]]></category>
		<category><![CDATA[hamming distance]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9880</guid>

					<description><![CDATA[You are given two string arrays,&#160;queries&#160;and&#160;dictionary. All words in each array comprise of lowercase English letters and have the same length. In one&#160;edit&#160;you can take&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two string arrays,&nbsp;<code>queries</code>&nbsp;and&nbsp;<code>dictionary</code>. All words in each array comprise of lowercase English letters and have the same length.</p>



<p>In one&nbsp;<strong>edit</strong>&nbsp;you can take a word from&nbsp;<code>queries</code>, and change any letter in it to any other letter. Find all words from&nbsp;<code>queries</code>&nbsp;that, after a&nbsp;<strong>maximum</strong>&nbsp;of two edits, equal some word from&nbsp;<code>dictionary</code>.</p>



<p>Return<em>&nbsp;a list of all words from&nbsp;</em><code>queries</code><em>,&nbsp;</em><em>that match with some word from&nbsp;</em><code>dictionary</code><em>&nbsp;after a maximum of&nbsp;<strong>two edits</strong></em>. Return the words in the&nbsp;<strong>same order</strong>&nbsp;they appear in&nbsp;<code>queries</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> queries = ["word","note","ants","wood"], dictionary = ["wood","joke","moat"]
<strong>Output:</strong> ["word","note","wood"]
<strong>Explanation:</strong>
- Changing the 'r' in "word" to 'o' allows it to equal the dictionary word "wood".
- Changing the 'n' to 'j' and the 't' to 'k' in "note" changes it to "joke".
- It would take more than 2 edits for "ants" to equal a dictionary word.
- "wood" can remain unchanged (0 edits) and match the corresponding dictionary word.
Thus, we return ["word","note","wood"].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> queries = ["yes"], dictionary = ["not"]
<strong>Output:</strong> []
<strong>Explanation:</strong>
Applying any two edits to "yes" cannot make it equal to "not". Thus, we return an empty array.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= queries.length, dictionary.length &lt;= 100</code></li><li><code>n == queries[i].length == dictionary[j].length</code></li><li><code>1 &lt;= n &lt;= 100</code></li><li>All&nbsp;<code>queries[i]</code>&nbsp;and&nbsp;<code>dictionary[j]</code>&nbsp;are composed of lowercase English letters.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Hamming distance + Brute Force</strong></h2>



<p>For each query word q, check the hamming distance between it and all words in the dictionary.</p>



<p>Time complexity: O(|q|*|d|*n)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;string&gt; twoEditWords(vector&lt;string&gt;&amp; queries, vector&lt;string&gt;&amp; dictionary) {
    const int n = queries[0].size();
    auto check = [&amp;](string_view q) {      
      for (const string&amp; w : dictionary) {
        int dist = 0;
        for (int i = 0; i &lt; n &amp;&amp; dist &lt;= 3; ++i)
          dist += q[i] != w[i];
        if (dist &lt;= 2) return true;
      }
      return false;
    };
    vector&lt;string&gt; ans;
    for (const string&amp; q : queries) 
      if (check(q)) ans.push_back(q);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2452-words-within-two-edits-of-dictionary%ef%bf%bc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2451. Odd String Difference</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2451-odd-string-difference%ef%bf%bc/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2451-odd-string-difference%ef%bf%bc/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 31 Oct 2022 16:18:48 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[difference]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9874</guid>

					<description><![CDATA[You are given an array of equal-length strings&#160;words. Assume that the length of each string is&#160;n. Each string&#160;words[i]&#160;can be converted into a&#160;difference integer array&#160;difference[i]&#160;of length&#160;n&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of equal-length strings&nbsp;<code>words</code>. Assume that the length of each string is&nbsp;<code>n</code>.</p>



<p>Each string&nbsp;<code>words[i]</code>&nbsp;can be converted into a&nbsp;<strong>difference integer array</strong>&nbsp;<code>difference[i]</code>&nbsp;of length&nbsp;<code>n - 1</code>&nbsp;where&nbsp;<code>difference[i][j] = words[i][j+1] - words[i][j]</code>&nbsp;where&nbsp;<code>0 &lt;= j &lt;= n - 2</code>. Note that the difference between two letters is the difference between their&nbsp;<strong>positions</strong>&nbsp;in the alphabet i.e.&nbsp;the position of&nbsp;<code>'a'</code>&nbsp;is&nbsp;<code>0</code>,&nbsp;<code>'b'</code>&nbsp;is&nbsp;<code>1</code>, and&nbsp;<code>'z'</code>&nbsp;is&nbsp;<code>25</code>.</p>



<ul class="wp-block-list"><li>For example, for the string&nbsp;<code>"acb"</code>, the difference integer array is&nbsp;<code>[2 - 0, 1 - 2] = [2, -1]</code>.</li></ul>



<p>All the strings in words have the same difference integer array,&nbsp;<strong>except one</strong>. You should find that string.</p>



<p>Return<em>&nbsp;the string in&nbsp;</em><code>words</code><em>&nbsp;that has different&nbsp;<strong>difference integer array</strong>.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["adc","wzy","abc"]
<strong>Output:</strong> "abc"
<strong>Explanation:</strong> 
- The difference integer array of "adc" is [3 - 0, 2 - 3] = [3, -1].
- The difference integer array of "wzy" is [25 - 22, 24 - 25]= [3, -1].
- The difference integer array of "abc" is [1 - 0, 2 - 1] = [1, 1]. 
The odd array out is [1, 1], so we return the corresponding string, "abc".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["aaa","bob","ccc","ddd"]
<strong>Output:</strong> "bob"
<strong>Explanation:</strong> All the integer arrays are [0, 0] except for "bob", which corresponds to [13, -13].
</pre>



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



<ul class="wp-block-list"><li><code>3 &lt;= words.length &lt;= 100</code></li><li><code>n == words[i].length</code></li><li><code>2 &lt;= n &lt;= 20</code></li><li><code>words[i]</code>&nbsp;consists of lowercase English letters.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Comparing with first string.</strong></h2>



<p>Let us pick words[0] as a reference for comparison, assuming it&#8217;s valid. If we only found one instance say words[i], that is different than words[0], we know that words[i] is bad, otherwise we should see m &#8211; 1 different words which means words[0] itself is bad.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string oddString(vector&lt;string&gt;&amp; words) {
    const int m = words.size();
    const int n = words[0].size();
    int count = 0;
    int bad = 0;
    for (int i = 1; i &lt; m; ++i) 
      for (int j = 1; j &lt; n; ++j) {
        if (words[i][j] - words[i][j - 1] 
           != words[0][j] - words[0][j - 1]) {
          ++count;
          bad = i;
          break;
        }
      }
    return words[count == 1 ? bad : 0];
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2451-odd-string-difference%ef%bf%bc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2315. Count Asterisks</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2315-count-asterisks/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2315-count-asterisks/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Jun 2022 20:38:13 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9757</guid>

					<description><![CDATA[You are given a string&#160;s, where every&#160;two&#160;consecutive vertical bars&#160;'&#124;'&#160;are grouped into a&#160;pair. In other words, the 1st&#160;and 2nd&#160;'&#124;'&#160;make a pair, the 3rd&#160;and 4th&#160;'&#124;'&#160;make a pair,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a string&nbsp;<code>s</code>, where every&nbsp;<strong>two</strong>&nbsp;consecutive vertical bars&nbsp;<code>'|'</code>&nbsp;are grouped into a&nbsp;<strong>pair</strong>. In other words, the 1<sup>st</sup>&nbsp;and 2<sup>nd</sup>&nbsp;<code>'|'</code>&nbsp;make a pair, the 3<sup>rd</sup>&nbsp;and 4<sup>th</sup>&nbsp;<code>'|'</code>&nbsp;make a pair, and so forth.</p>



<p>Return&nbsp;<em>the number of&nbsp;</em><code>'*'</code><em>&nbsp;in&nbsp;</em><code>s</code><em>,&nbsp;<strong>excluding</strong>&nbsp;the&nbsp;</em><code>'*'</code><em>&nbsp;between each pair of&nbsp;</em><code>'|'</code>.</p>



<p><strong>Note</strong>&nbsp;that each&nbsp;<code>'|'</code>&nbsp;will belong to&nbsp;<strong>exactly</strong>&nbsp;one pair.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "l|*e*et|c**o|*de|"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The considered characters are underlined: "l|*e*et|c**o|*de|".
The characters between the first and second '|' are excluded from the answer.
Also, the characters between the third and fourth '|' are excluded from the answer.
There are 2 asterisks considered. Therefore, we return 2.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "iamprogrammer"
<strong>Output:</strong> 0
<strong>Explanation:</strong> In this example, there are no asterisks in s. Therefore, we return 0.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "yo|uar|e**|b|e***au|tifu|l"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The considered characters are underlined: "yo|uar|e**|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5.</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= s.length &lt;= 1000</code></li><li><code>s</code>&nbsp;consists of lowercase English letters, vertical bars&nbsp;<code>'|'</code>, and asterisks&nbsp;<code>'*'</code>.</li><li><code>s</code>&nbsp;contains an&nbsp;<strong>even</strong>&nbsp;number of vertical bars&nbsp;<code>'|'</code>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Counting</strong></h2>



<p>Count the number of bars so far, and only count &#8216;*&#8217; when there are even number of bars on the left.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int countAsterisks(string s) {
    int bars = 0;
    int ans = 0;    
    for (char c : s) {
      if (c == '*' &amp;&amp; bars % 2 == 0)
        ++ans;
      if (c == '|') ++bars;      
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2315-count-asterisks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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[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;]]></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 class="wp-block-list"><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 class="wp-block-list"><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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 2264. Largest 3-Same-Digit Number in String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2264-largest-3-same-digit-number-in-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2264-largest-3-same-digit-number-in-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 May 2022 06:52:40 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9725</guid>

					<description><![CDATA[You are given a string&#160;num&#160;representing a large integer. An integer is&#160;good&#160;if it meets the following conditions: It is a&#160;substring&#160;of&#160;num&#160;with length&#160;3. It consists of only one&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a string&nbsp;<code>num</code>&nbsp;representing a large integer. An integer is&nbsp;<strong>good</strong>&nbsp;if it meets the following conditions:</p>



<ul class="wp-block-list"><li>It is a&nbsp;<strong>substring</strong>&nbsp;of&nbsp;<code>num</code>&nbsp;with length&nbsp;<code>3</code>.</li><li>It consists of only one unique digit.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum good&nbsp;</strong>integer as a&nbsp;<strong>string</strong>&nbsp;or an empty string&nbsp;</em><code>""</code><em>&nbsp;if no such integer exists</em>.</p>



<p>Note:</p>



<ul class="wp-block-list"><li>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous sequence of characters within a string.</li><li>There may be&nbsp;<strong>leading zeroes</strong>&nbsp;in&nbsp;<code>num</code>&nbsp;or a good integer.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "6<strong><u>777</u></strong>133339"
<strong>Output:</strong> "777"
<strong>Explanation:</strong> There are two distinct good integers: "777" and "333".
"777" is the largest, so we return "777".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "23<strong><u>000</u></strong>19"
<strong>Output:</strong> "000"
<strong>Explanation:</strong> "000" is the only good integer.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "42352338"
<strong>Output:</strong> ""
<strong>Explanation:</strong> No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.
</pre>



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



<ul class="wp-block-list"><li><code>3 &lt;= num.length &lt;= 1000</code></li><li><code>num</code>&nbsp;only consists of digits.</li></ul>



<p><strong>Solution:</strong></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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string largestGoodInteger(string num) {
    string ans;
    for (int i = 0; i &lt; num.size() - 2; ++i) {
      if (num[i] == num[i + 1] &amp;&amp; num[i] == num[i + 2] &amp;&amp; 
         (ans.empty() || num[i] &gt; ans[0]))
        ans = num.substr(i, 3);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2264-largest-3-same-digit-number-in-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2255. Count Prefixes of a Given String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2255-count-prefixes-of-a-given-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2255-count-prefixes-of-a-given-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 May 2022 05:25:24 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9703</guid>

					<description><![CDATA[You are given a string array&#160;words&#160;and a string&#160;s, where&#160;words[i]&#160;and&#160;s&#160;comprise only of&#160;lowercase English letters. Return&#160;the&#160;number of strings&#160;in&#160;words&#160;that are a&#160;prefix&#160;of&#160;s. A&#160;prefix&#160;of a string is a substring that&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a string array&nbsp;<code>words</code>&nbsp;and a string&nbsp;<code>s</code>, where&nbsp;<code>words[i]</code>&nbsp;and&nbsp;<code>s</code>&nbsp;comprise only of&nbsp;<strong>lowercase English letters</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>number of strings</strong>&nbsp;in</em>&nbsp;<code>words</code>&nbsp;<em>that are a&nbsp;<strong>prefix</strong>&nbsp;of</em>&nbsp;<code>s</code>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["a","b","c","ab","bc","abc"], s = "abc"
<strong>Output:</strong> 3
<strong>Explanation:</strong>
The strings in words which are a prefix of s = "abc" are:
"a", "ab", and "abc".
Thus the number of strings in words which are a prefix of s is 3.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["a","a"], s = "aa"
<strong>Output:</strong> 2
<strong>Explanation:
</strong>Both of the strings are a prefix of s. 
Note that the same string can occur multiple times in words, and it should be counted each time.</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= words.length &lt;= 1000</code></li><li><code>1 &lt;= words[i].length, s.length &lt;= 10</code></li><li><code>words[i]</code>&nbsp;and&nbsp;<code>s</code>&nbsp;consist of lowercase English letters&nbsp;<strong>only</strong>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Brute Force</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int countPrefixes(vector&lt;string&gt;&amp; words, string s) {
    return count_if(begin(words), end(words), [&amp;s](const string&amp; word) {
      return s.find(word) == 0;
    });
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2255-count-prefixes-of-a-given-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2243. Calculate Digit Sum of a String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2243-calculate-digit-sum-of-a-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2243-calculate-digit-sum-of-a-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Apr 2022 22:33:20 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9676</guid>

					<description><![CDATA[You are given a string&#160;s&#160;consisting of digits and an integer&#160;k. A&#160;round&#160;can be completed if the length of&#160;s&#160;is greater than&#160;k. In one round, do the following:&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a string&nbsp;<code>s</code>&nbsp;consisting of digits and an integer&nbsp;<code>k</code>.</p>



<p>A&nbsp;<strong>round</strong>&nbsp;can be completed if the length of&nbsp;<code>s</code>&nbsp;is greater than&nbsp;<code>k</code>. In one round, do the following:</p>



<ol class="wp-block-list"><li><strong>Divide</strong>&nbsp;<code>s</code>&nbsp;into&nbsp;<strong>consecutive groups</strong>&nbsp;of size&nbsp;<code>k</code>&nbsp;such that the first&nbsp;<code>k</code>&nbsp;characters are in the first group, the next&nbsp;<code>k</code>&nbsp;characters are in the second group, and so on.&nbsp;<strong>Note</strong>&nbsp;that the size of the last group can be smaller than&nbsp;<code>k</code>.</li><li><strong>Replace</strong>&nbsp;each group of&nbsp;<code>s</code>&nbsp;with a string representing the sum of all its digits. For example,&nbsp;<code>"346"</code>&nbsp;is replaced with&nbsp;<code>"13"</code>&nbsp;because&nbsp;<code>3 + 4 + 6 = 13</code>.</li><li><strong>Merge</strong>&nbsp;consecutive groups together to form a new string. If the length of the string is greater than&nbsp;<code>k</code>, repeat from step&nbsp;<code>1</code>.</li></ol>



<p>Return&nbsp;<code>s</code>&nbsp;<em>after all rounds have been completed</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "11111222223", k = 3
<strong>Output:</strong> "135"
<strong>Explanation:</strong> 
- For the first round, we divide s into groups of size 3: "111", "112", "222", and "23".
  ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. 
&nbsp; So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round.
- For the second round, we divide s into "346" and "5".
&nbsp; Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. 
&nbsp; So, s becomes "13" + "5" = "135" after second round. 
Now, s.length &lt;= k, so we return "135" as the answer.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "00000000", k = 3
<strong>Output:</strong> "000"
<strong>Explanation:</strong> 
We divide s into "000", "000", and "00".
Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. 
s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000".
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= s.length &lt;= 100</code></li><li><code>2 &lt;= k &lt;= 100</code></li><li><code>s</code>&nbsp;consists of digits only.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: </strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string digitSum(string s, int k) {
    while (s.length() &gt; k) {
      string ss;
      for (int j = 0; j &lt; s.length(); j += k) {
        int sum = 0;
        for (int i = 0; i &lt; k &amp;&amp; i + j &lt; s.length(); ++i)
          sum += (s[j + i] - '0');
        ss += to_string(sum);
      }
      ss.swap(s);
    }
    return s;            
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2243-calculate-digit-sum-of-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2232. Minimize Result by Adding Parentheses to Expression</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2232-minimize-result-by-adding-parentheses-to-expression/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2232-minimize-result-by-adding-parentheses-to-expression/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Apr 2022 06:20:27 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9636</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;string&#160;expression&#160;of the form&#160;"&#60;num1&#62;+&#60;num2&#62;"&#160;where&#160;&#60;num1&#62;&#160;and&#160;&#60;num2&#62;&#160;represent positive integers. Add a pair of parentheses to&#160;expression&#160;such that after the addition of parentheses,&#160;expression&#160;is a&#160;valid&#160;mathematical expression and evaluates to&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;string&nbsp;<code>expression</code>&nbsp;of the form&nbsp;<code>"&lt;num1&gt;+&lt;num2&gt;"</code>&nbsp;where&nbsp;<code>&lt;num1&gt;</code>&nbsp;and&nbsp;<code>&lt;num2&gt;</code>&nbsp;represent positive integers.</p>



<p>Add a pair of parentheses to&nbsp;<code>expression</code>&nbsp;such that after the addition of parentheses,&nbsp;<code>expression</code>&nbsp;is a&nbsp;<strong>valid</strong>&nbsp;mathematical expression and evaluates to the&nbsp;<strong>smallest</strong>&nbsp;possible value. The left parenthesis&nbsp;<strong>must</strong>&nbsp;be added to the left of&nbsp;<code>'+'</code>&nbsp;and the right parenthesis&nbsp;<strong>must</strong>&nbsp;be added to the right of&nbsp;<code>'+'</code>.</p>



<p>Return&nbsp;<code>expression</code><em>&nbsp;after adding a pair of parentheses such that&nbsp;</em><code>expression</code><em>&nbsp;evaluates to the&nbsp;<strong>smallest</strong>&nbsp;possible value.</em>&nbsp;If there are multiple answers that yield the same result, return any of them.</p>



<p>The input has been generated such that the original value of&nbsp;<code>expression</code>, and the value of&nbsp;<code>expression</code>&nbsp;after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "247+38"
<strong>Output:</strong> "2(47+38)"
<strong>Explanation:</strong> The <code>expression</code> evaluates to 2 * (47 + 38) = 2 * 85 = 170.
Note that "2(4)7+38" is invalid because the right parenthesis must be to the right of the <code>'+'</code>.
It can be shown that 170 is the smallest possible value.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "12+34"
<strong>Output:</strong> "1(2+3)4"
<strong>Explanation:</strong> The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "999+999"
<strong>Output:</strong> "(999+999)"
<strong>Explanation:</strong> The <code>expression</code> evaluates to 999 + 999 = 1998.
</pre>



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



<ul class="wp-block-list"><li><code>3 &lt;= expression.length &lt;= 10</code></li><li><code>expression</code>&nbsp;consists of digits from&nbsp;<code>'1'</code>&nbsp;to&nbsp;<code>'9'</code>&nbsp;and&nbsp;<code>'+'</code>.</li><li><code>expression</code>&nbsp;starts and ends with digits.</li><li><code>expression</code>&nbsp;contains exactly one&nbsp;<code>'+'</code>.</li><li>The original value of&nbsp;<code>expression</code>, and the value of&nbsp;<code>expression</code>&nbsp;after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Brute Force</strong></h2>



<p>Try all possible positions to add parentheses and evaluate the new expression.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string minimizeResult(string expression) {
    const int n = expression.size();
    auto p = expression.find('+');
    int best = INT_MAX;
    string ans;
    for (int l = 0; l &lt; p; ++l)
      for (int r = p + 2; r &lt; n + 1; ++r) {
        const int m1 = l ? stoi(expression.substr(0, l)) : 1;
        const int m2 = (r &lt; n) ? stoi(expression.substr(r)) : 1;
        const int n1 = stoi(expression.substr(l, p));
        const int n2 = stoi(expression.substr(p + 1, r - p - 1));
        const int cur = m1 * (n1 + n2) * m2;
        if (cur &lt; best) {
          best = cur;
          ans = expression;
          ans.insert(l, &quot;(&quot;);
          ans.insert(r + 1, &quot;)&quot;);
        }
      }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2232-minimize-result-by-adding-parentheses-to-expression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
