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:
"abba"
, str = "dog cat cat dog"
should return true."abba"
, str = "dog cat cat fish"
should return false."aaaa"
, str = "dog cat cat dog"
should return false."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.
判断字符串是否是模式串的形式。
对字符串进行分词,用map保存和模式串字符的对应关系
class Solution {
public:
bool wordPattern(string pattern, string str) {
str += " ";
int j = 0;
unordered_map<string, string> mp;
for(int i = 0; i < str.size(); i++)
{
int pos = str.find(" ", i);
string tmp = str.substr(i, pos - i);
i = pos;
if(j == pattern.size()) return false;
string key(pattern[j] + "\0");
if(mp.find(key) == mp.end())
{
if(mp.find(tmp) == mp.end())
{
mp[tmp] = key;
mp[key] = tmp;
}
else return false;
}
else if(mp[key] != tmp) return false;
j++;
}
if(j != pattern.size()) return false;
return true;
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有