290. Word Pattern
来源:互联网 发布:中国十大zu最恶心公知 编辑:程序博客网 时间:2024/06/06 05:07
1.Question
Given a pattern
and a string str
, find if str
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern
and a non-empty word in str
.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.
codeA
class Solution {public: bool wordPattern(string pattern, string str) { unordered_map<char, int> map1; unordered_map<string, int> map2; int label = 1; for(int i = 0; i < pattern.size(); i++) { if(str.empty()) return false; char tempchar = pattern[i]; string tempstring; int location = str.find(" "); if(location == -1) { tempstring = str.substr(0, str.size()); str.erase(0, str.size() + 1); } else { tempstring = str.substr(0, location); str.erase(0, location + 1); } if(map1.find(tempchar) != map1.end() || map2.find(tempstring) != map2.end()) { if(map1[tempchar] != map2[tempstring]) return false; } else { map1[tempchar] = label; map2[tempstring] = label; label++; } } return str.empty(); }};
codeB
class Solution {public: bool wordPattern(string pattern, string str) { unordered_map<char, int> map1; unordered_map<string, int> map2; istringstream stream(str); int label = 1; string word; while(stream >> word) { char character = pattern[label - 1]; if(map1.find(character) != map1.end() || map2.find(word) != map2.end()) { if(map1[character] != map2[word]) return false; } else { map1[character] = label; map2[word] = label; } label++; } return label -1 == pattern.size(); }};
3.Note
a. 本题思想也比较简单,就是通过两个哈希表进行映射,让pattern 和str 有对应的映射。关键是,怎么把str 的单词分割出来。codeA 是最初想的,通过找分割标志符号来找单词的末位置,然后提出单词,并在str 中删掉,以便下次找单词。这种方法的好处是,分割标志符号不限定于" "。codeB 则利用了istringstream,但分隔标志符号只能是" "。具体用法看代码。
b. substr和erase的用法:substr(start, length).
0 0
- 【leetcode】290. Word Pattern
- 【leetcode】290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern LeetCode
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- Leetcode 290. Word Pattern
- 290. Word Pattern
- 【LeetCode】290. Word Pattern
- 290. Word Pattern
- LeetCode-290. Word Pattern
- LeetCode *** 290. Word Pattern
- echarts.min.js 报错
- Java设计模式
- Xcode以及其他平台主题
- Win7 和 MAC 系统通过VMware共享文件夹
- KMP算法之while循环部分
- 290. Word Pattern
- Java入门习题(三)——初始化
- 序列操作
- Altium 用左键框选后会出现十字光标,且显示为Select a reference piont
- C Variable
- c++实验5
- 定制开机画面
- [小技巧]如何一键查询linux服务器的信息
- 深入理解Nginx第四章:HTTP配置项的步骤整理