<?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>words Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/words/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/words/</link>
	<description></description>
	<lastBuildDate>Sun, 09 Jan 2022 07:30:08 +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>words Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/words/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2129. Capitalize the Title</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2129-capitalize-the-title/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2129-capitalize-the-title/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 Jan 2022 07:26:24 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[split]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[words]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9411</guid>

					<description><![CDATA[<p>You are given a string&#160;title&#160;consisting of one or more words separated by a single space, where each word consists of English letters.&#160;Capitalize&#160;the string by changing&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-2129-capitalize-the-title/">花花酱 LeetCode 2129. Capitalize the Title</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>title</code>&nbsp;consisting of one or more words separated by a single space, where each word consists of English letters.&nbsp;<strong>Capitalize</strong>&nbsp;the string by changing the capitalization of each word such that:</p>



<ul><li>If the length of the word is&nbsp;<code>1</code>&nbsp;or&nbsp;<code>2</code>&nbsp;letters, change all letters to lowercase.</li><li>Otherwise, change the first letter to uppercase and the remaining letters to lowercase.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>capitalized</strong>&nbsp;</em><code>title</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> title = "capiTalIze tHe titLe"
<strong>Output:</strong> "Capitalize The Title"
<strong>Explanation:</strong>
Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> title = "First leTTeR of EACH Word"
<strong>Output:</strong> "First Letter of Each Word"
<strong>Explanation:</strong>
The word "of" has length 2, so it is all lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> title = "i lOve leetcode"
<strong>Output:</strong> "i Love Leetcode"
<strong>Explanation:</strong>
The word "i" has length 1, so it is lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.
</pre>



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



<ul><li><code>1 &lt;= title.length &lt;= 100</code></li><li><code>title</code>&nbsp;consists of words separated by a single space without any leading or trailing spaces.</li><li>Each word consists of uppercase and lowercase English letters and is&nbsp;<strong>non-empty</strong>.</li></ul>



<h2><strong>Solution: Straight forward</strong></h2>



<p>Without splitting the sentence into words, we need to take care the word of length one and two.</p>



<p>Tips: use std::tolower, std::toupper to transform letters.</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 capitalizeTitle(string title) {
    const int n = title.size();
    for (int i = 0; i &lt; title.size(); ++i) {
      if ((i == 0 || title[i - 1] == ' ') 
          &amp;&amp; i + 2 &lt; n &amp;&amp; title[i + 1] != ' ' &amp;&amp; title[i + 2] != ' ')
        title[i] = toupper(title[i]);
      else
        title[i] = tolower(title[i]);         
    }
    return title;
  }
};</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def capitalizeTitle(self, title: str) -&gt; str:
    return &quot; &quot;.join(map(lambda w: w.lower() if len(w) &lt;= 2 else w[0].upper() + w[1:].lower(), title.split()))</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-2129-capitalize-the-title/">花花酱 LeetCode 2129. Capitalize the Title</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-2129-capitalize-the-title/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1859. Sorting the Sentence</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1859-sorting-the-sentence/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1859-sorting-the-sentence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 29 May 2021 22:47:12 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[words]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8456</guid>

					<description><![CDATA[<p>A&#160;sentence&#160;is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1859-sorting-the-sentence/">花花酱 LeetCode 1859. Sorting the Sentence</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>sentence</strong>&nbsp;is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.</p>



<p>A sentence can be&nbsp;<strong>shuffled</strong>&nbsp;by appending the&nbsp;<strong>1-indexed word position</strong>&nbsp;to each word then rearranging the words in the sentence.</p>



<ul><li>For example, the sentence&nbsp;<code>"This is a sentence"</code>&nbsp;can be shuffled as&nbsp;<code>"sentence4 a3 is2 This1"</code>&nbsp;or&nbsp;<code>"is2 sentence4 This1 a3"</code>.</li></ul>



<p>Given a&nbsp;<strong>shuffled sentence</strong>&nbsp;<code>s</code>&nbsp;containing no more than&nbsp;<code>9</code>&nbsp;words, reconstruct and return&nbsp;<em>the original sentence</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "is2 sentence4 This1 a3"
<strong>Output:</strong> "This is a sentence"
<strong>Explanation:</strong> Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "Myself2 Me1 I4 and3"
<strong>Output:</strong> "Me Myself and I"
<strong>Explanation:</strong> Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
</pre>



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



<ul><li><code>2 &lt;= s.length &lt;= 200</code></li><li><code>s</code>&nbsp;consists of lowercase and uppercase English letters, spaces, and digits from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>9</code>.</li><li>The number of words in&nbsp;<code>s</code>&nbsp;is between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>9</code>.</li><li>The words in&nbsp;<code>s</code>&nbsp;are separated by a single space.</li><li><code>s</code>&nbsp;contains no leading or trailing spaces.</li></ul>



<h2><strong>Solution: String</strong></h2>



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



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

<pre class="crayon-plain-tag">class Solution:
  def sortSentence(self, s: str) -&gt; str:
    p = [(w[:-1], int(w[-1])) for w in s.split()]
    p.sort(key=lambda x : x[1])
    return &quot; &quot;.join((w for w, _ in p))</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1859-sorting-the-sentence/">花花酱 LeetCode 1859. Sorting the Sentence</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-1859-sorting-the-sentence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 557 Reverse Words in a String III</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-557-reverse-words-in-a-string-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-557-reverse-words-in-a-string-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 03 Mar 2018 07:43:42 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[reversed]]></category>
		<category><![CDATA[words]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1925</guid>

					<description><![CDATA[<p>题目大意：独立反转字符串中的每个单词。 Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-557-reverse-words-in-a-string-iii/">花花酱 LeetCode 557 Reverse Words in a String III</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>题目大意：独立反转字符串中的每个单词。</p>
<p>Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: &quot;Let's take LeetCode contest&quot;
Output: &quot;s'teL ekat edoCteeL tsetnoc&quot;</pre><p><b>Note:</b> In the string, each word is separated by single space and there will not be any extra space in the string.</p>
<p><strong>Idea: Brute Force</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 23 ms
class Solution {
public:
  string reverseWords(string s) {    
    int index = 0;  
    for (int i = 0; i &lt;= s.length(); ++i) {
      if (i == s.length() || s[i] == ' ') {
        std::reverse(s.begin() + index, s.begin() + i);
        index = i + 1;
      }
    }
    return s;
  }
};</pre><p>&nbsp;</p>
<p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 44 ms (beats 100%)
"""
class Solution:
  def reverseWords(self, s):        
    return ' '.join(map(lambda x: x[::-1], s.split(' ')))</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-557-reverse-words-in-a-string-iii/">花花酱 LeetCode 557 Reverse Words in a String III</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-557-reverse-words-in-a-string-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 734. Sentence Similarity</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 28 Nov 2017 22:17:26 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[words]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1006</guid>

					<description><![CDATA[<p>Problem: Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. For&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/">花花酱 LeetCode 734. Sentence Similarity</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/KAX277fYKMM?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given two sentences <code>words1, words2</code> (each represented as an array of strings), and a list of similar word pairs <code>pairs</code>, determine if two sentences are similar.</p>
<p>For example, &#8220;great acting skills&#8221; and &#8220;fine drama talent&#8221; are similar, if the similar word pairs are <code>pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]</code>.</p>
<p>Note that the similarity relation is not transitive. For example, if &#8220;great&#8221; and &#8220;fine&#8221; are similar, and &#8220;fine&#8221; and &#8220;good&#8221; are similar, &#8220;great&#8221; and &#8220;good&#8221; are <b>not</b> necessarily similar.</p>
<p>However, similarity is symmetric. For example, &#8220;great&#8221; and &#8220;fine&#8221; being similar is the same as &#8220;fine&#8221; and &#8220;great&#8221; being similar.</p>
<p>Also, a word is always similar with itself. For example, the sentences <code>words1 = ["great"], words2 = ["great"], pairs = []</code> are similar, even though there are no specified similar word pairs.</p>
<p>Finally, sentences can only be similar if they have the same number of words. So a sentence like <code>words1 = ["great"]</code> can never be similar to <code>words2 = ["doubleplus","good"]</code>.</p>
<p><b>Note:</b></p>
<ul>
<li>The length of <code>words1</code> and <code>words2</code> will not exceed <code>1000</code>.</li>
<li>The length of <code>pairs</code> will not exceed <code>2000</code>.</li>
<li>The length of each <code>pairs[i]</code> will be <code>2</code>.</li>
<li>The length of each <code>words[i]</code> and <code>pairs[i][j]</code> will be in the range <code>[1, 20]</code>.</li>
</ul>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p>题目大意：</p>
<p>给你两个句子（由单词数组表示）和一些近义词对，问你这两个句子是否相似，即每组相对应的单词都要相似。</p>
<p>注意相似性不能传递，比如给只你&#8221;great&#8221;和&#8221;fine&#8221;相似、&#8221;fine&#8221;和&#8221;good&#8221;相似，这种情况下&#8221;great&#8221;和&#8221;good&#8221;不相似。</p>
<p><strong>Idea:</strong></p>
<p>Use hashtable to store mapping from word to its similar words.</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117.png"><img class="alignnone size-full wp-image-1028" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<h1><strong>Solution: HashTable</strong></h1>
<p>Time complexity: O(|pairs| + |words1|)</p>
<p>Space complexity: O(|pairs|)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 9 ms
class Solution {
public:
    bool areSentencesSimilar(vector&lt;string&gt;&amp; words1, vector&lt;string&gt;&amp; words2, vector&lt;pair&lt;string, string&gt;&gt; pairs) {
        if (words1.size() != words2.size()) return false;
        
        unordered_map&lt;string, unordered_set&lt;string&gt;&gt; similar_words;
        for (const auto&amp; pair : pairs) {            
            similar_words[pair.first].insert(pair.second);
            similar_words[pair.second].insert(pair.first);
        }
        
        for (int i = 0; i &lt; words1.size(); ++i) {
            if (words1[i] == words2[i]) continue;
            if (!similar_words[words1[i]].count(words2[i])) return false;
        }
        
        return true;
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 10 ms
class Solution {
    public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) {
        if (words1.length != words2.length) return false;
        
        Map&lt;String, Set&lt;String&gt;&gt; similar_words = new HashMap&lt;&gt;();
        
        for (String[] pair : pairs) {
            if (!similar_words.containsKey(pair[0]))
                similar_words.put(pair[0], new HashSet&lt;&gt;());
            if (!similar_words.containsKey(pair[1]))
                similar_words.put(pair[1], new HashSet&lt;&gt;());
            similar_words.get(pair[0]).add(pair[1]);
            similar_words.get(pair[1]).add(pair[0]);
        }
        
        for (int i = 0; i &lt; words1.length; ++i) {
            if (words1[i].equals(words2[i])) continue;
            if (!similar_words.containsKey(words1[i])) return false;
            if (!similar_words.get(words1[i]).contains(words2[i])) return false;
        }
        
        return true;
    }
}</pre><p></div><h2 class="tabtitle">Python</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 62 ms
"""
class Solution:
    def areSentencesSimilar(self, words1, words2, pairs):
        if len(words1) != len(words2): return False
        
        similar_words = {}
        
        for w1, w2 in pairs:
            if not w1 in similar_words: similar_words[w1] = set()
            if not w2 in similar_words: similar_words[w2] = set()
            similar_words[w1].add(w2)
            similar_words[w2].add(w1)
        
        for w1, w2 in zip(words1, words2):
            if w1 == w2: continue
            if w1 not in similar_words: return False
            if w2 not in similar_words[w1]: return False
        
        return True</pre><p></div></div></p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-737-sentence-similarity-ii/">[解题报告] LeetCode 737. Sentence Similarity II</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/">花花酱 LeetCode 734. Sentence Similarity</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-734-sentence-similarity/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
