Leetcode NO.290 Word Pattern
2015-10-08 04:50
281 查看
本题题目要求如下:
Given a
find if
Examples:
pattern =
pattern =
pattern =
pattern =
Notes:
words separated by a single space. Each word in
letters.
Both
not have leading or trailing spaces.
Each letter in
本题应该算是easy中的easy了,思路相当直接,就是用hashmap,当然需要注意一点就是不光要避免'a'->"dog"和'a'->"cat"这种冲突,还要解决'a'->"dog"和'b'->dog这种冲突。。我的解决方法是加一个hashset,也许有更好地,但是这么做也行。。
代码如下:
class Solution {
public:
bool wordPattern(string pattern, string str) {
istringstream is(str);
unordered_map<char, string> hashmap;
unordered_set<string> hashset;
string word;
int sz = pattern.length();
int i = 0;
while (is >> word) {
hashset.insert(word);
if (i == sz) {
return false;
}
char tmp_val = pattern[i++];
auto found = hashmap.find(tmp_val);
if (found == hashmap.end()) {
hashmap[tmp_val] = word;
}
else {
if (hashmap[tmp_val] != word) {
return false;
}
}
}
return (hashset.size() == hashmap.size() and i == sz);
}
};
Given a
patternand a string
str,
find if
strfollows the same pattern.
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:
patterncontains only lowercase alphabetical letters, and
strcontains
words separated by a single space. Each word in
strcontains only lowercase alphabetical
letters.
Both
patternand
strdo
not have leading or trailing spaces.
Each letter in
patternmust map to a word with length that is at least 1.
本题应该算是easy中的easy了,思路相当直接,就是用hashmap,当然需要注意一点就是不光要避免'a'->"dog"和'a'->"cat"这种冲突,还要解决'a'->"dog"和'b'->dog这种冲突。。我的解决方法是加一个hashset,也许有更好地,但是这么做也行。。
代码如下:
class Solution {
public:
bool wordPattern(string pattern, string str) {
istringstream is(str);
unordered_map<char, string> hashmap;
unordered_set<string> hashset;
string word;
int sz = pattern.length();
int i = 0;
while (is >> word) {
hashset.insert(word);
if (i == sz) {
return false;
}
char tmp_val = pattern[i++];
auto found = hashmap.find(tmp_val);
if (found == hashmap.end()) {
hashmap[tmp_val] = word;
}
else {
if (hashmap[tmp_val] != word) {
return false;
}
}
}
return (hashset.size() == hashmap.size() and i == sz);
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- c语言实现hashmap(转载)
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C++联合体转换成C#结构的实现方法
- C#实现的算24点游戏算法实例分析
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题