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.
Example 1:
Input: pattern = “abba”, str = “dog cat cat dog”
Output: true
Example 2:
Input:pattern = “abba”, str = “dog cat cat fish”
Output: false
Example 3:
Input: pattern = “aaaa”, str = “dog cat cat dog”
Output: false
Example 4:
Input: pattern = “abba”, str = “dog dog dog dog”
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
题目大意:给定两个字符串pattern和str,pattern字符串表示模式,判断str字符串的模式是否和pattern一致,若一致返回true,不一致返回false。
代码:
class Solution {
public:
bool wordPattern(string pattern, string str){
unordered_map<string, char> hashmap;
unordered_map<char, string> phashmap;
int i = 0, j = 0, lens = str.size(), lenp = pattern.size();
while(i < lenp && j < lens){
int pos = str.find(' ', j);
string sub = str.substr(j, pos-j);
if(phashmap.count(pattern[i]) && phashmap[pattern[i]] != sub)
return false;
if(hashmap.count(sub) && hashmap[sub] != pattern[i] )
return false;
hashmap[sub] = pattern[i];
phashmap[pattern[i]] = sub;
++i;
j = pos+1;
//
}
return i == lenp && j == lens;
}
};
一个反思:开始看到这个题觉得是个水题,知道要把str和pattern对应起来,但是代码死活写不出来,尝试了自己写了个split把str按照空格每个词都分出来,然后for循环又写不好了,最后网上看了别人的思路才发现是自己最基本的数据结构没有掌握好,unorderedmap的许多用法都很模糊,对哈希表理解也不深刻,水题才是检验基础的标尺啊,很惭愧。