[LeetCode] Word Pattern

简介: This problem can be solved in very neat codes (yeah, you will see Stefan posting many nice solutions).

This problem can be solved in very neat codes (yeah, you will see Stefan posting many nice solutions).

The solution in the above link is so nice that I can almost do nothing to improve it instead of using unordered_map -_-

 1 class Solution {
 2 public:
 3     bool wordPattern(string pattern, string str) {
 4         unordered_map<char, int> p2i;
 5         unordered_map<string, int> w2i;
 6         istringstream in(str);
 7         int i = 0, n = pattern.length();
 8         for (string word; in >> word; i++) {
 9             if (i >= n || p2i[pattern[i]] != w2i[word])
10                 return false;
11             p2i[pattern[i]] = w2i[word] = i + 1;
12         }
13         return i == n;
14     }
15 };

If you wonder why it uses i + 1 instead of simply using i as the values, I mention it at the first comment in the above link :-)

目录
相关文章
LeetCode 318. Maximum Product of Word Lengths
给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。
53 0
LeetCode 318. Maximum Product of Word Lengths
LeetCode 290. Word Pattern
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。 这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。
31 0
LeetCode 290. Word Pattern
LeetCode 212. Word Search II
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
57 0
LeetCode 212. Word Search II
|
索引
LeetCode 79. Word Search
给定一个2D板和一个单词,找出该单词是否存在于网格中。 该单词可以由顺序相邻的单元的字母构成,其中“相邻”单元是水平或垂直相邻的单元。 相同的字母单元格不得多次使用。
49 0
LeetCode 79. Word Search
|
索引 存储
LeetCode 290 Word Pattern(单词模式)(istringstream、vector、map)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50611509 翻译 给定一个模式,和一个字符串str,返回str是否符合相同的模式。
940 0
LeetCode 58 Length of Last Word(最后单词的长度)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50592917 翻译 给定一个包含大小写字母和空格字符的字符串, 返回该字符串中最后一个单词的长度。
709 0
|
4天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
8 0