一. 题目来源:
lettcode: 290 word pattern
二, 题目大意:
给定两个字符串,其中一个是模板,一个是匹配串,模板是如aabb型的字符串,匹配串是由空格隔开的几个字符串
比如说:
- 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.
三. 解题思路:
看到这个字符串模板问题,我的第一想法是用一个map,将模板串中的每个字符和匹配串的字符串映射在一起,然后开始对模板串的字符开始逐个
遍历,判断此位置上相对应的字符串是不是映射在一起的那个字符串,若是,则继续遍历,若不是,则返回false,时间效率是pattern.size() *
map中find时间, 代码如下:
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> res;
set<string> s;
map<char, string> m;
res.clear();
s.clear();
m.clear();
split(str, " ", res);
if(pattern.size() != res.size())
return false;
for(unsigned i = 0; i < pattern.size(); i++){
if(m.find(pattern[i]) == m.end() && s.find(res[i]) == s.end())
m[pattern[i]] = res[i];
else if(m[pattern[i]] != res[i]) return false;
else if(m.find(pattern[i]) == m.end() && s.find(res[i]) != s.end())
return false;
}
return true;
}
void split(std::string& str, std::string c, vector<string>& res){
int pos1, pos2;
pos1 = 0;
pos2 = str.find(c);
while(pos2 != string::npos){
res.push_back(str.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
pos2 = str.find(c, pos1);
}
return;
}
};