Given a pattern and a string str, find if str follows 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 str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters.
Both pattern and str do not have leading or trailing spaces.
Each letter in pattern must map to a word with length that is at least 1.
思路:由于pattern中的字符 和str中的单词是一一对应的,因此用了两个哈希表,代码如下:
class Solution {
public:
bool wordPattern(string pattern, string str) {
map<char, string>hmap;
map<string, char>hmapp;
int lenp = pattern.length();
int lens = str.length();
int i = 0, j =0, index = 0;
while(i < lenp && j < lens){
while(str[j] != ' ' && j < lens)
j++;
string tmp = str.substr(index, j - index);
if(!hmap.count(pattern[i]))
hmap.insert(pair<char, string>(pattern[i], tmp));
else if(hmap[pattern[i]] != tmp)
return false;
if(!hmapp.count(tmp))
hmapp.insert(pair<string, char>(tmp, pattern[i]));
else if(hmapp[tmp] != pattern[i])
return false;
i++;
j++;
index = j;
}
if(i < lenp || j < lens)
return false;
return true;
}
};