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:
- 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:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> words;
int leftIdx = 0;
int rightIdx = 0;
while (rightIdx < str.size())
{
while (rightIdx < str.size() && str[rightIdx] != ' ')
rightIdx++;
words.push_back(str.substr(leftIdx, rightIdx-leftIdx));
leftIdx = rightIdx+1;
rightIdx = rightIdx+1;
}
if (pattern.size() != words.size())
return false;
map<char, string> matchTable;
map<string, char> reverseTable;
for (int i=0; i<pattern.size(); i++)
{
if (matchTable.count(pattern[i]) == 0 && reverseTable.count(words[i]) == 0)
{
matchTable[pattern[i]] = words[i];
reverseTable[words[i]] = pattern[i];
}
else
{
if (matchTable.count(pattern[i]) != 0 && reverseTable.count(words[i]) != 0)
{
if (words[i] == matchTable[pattern[i]] && pattern[i] == reverseTable[words[i]])
{
continue;
}
}
return false;
}
}
return true;
}
};
字符串模式匹配算法

本文介绍了一种用于判断给定字符串是否遵循指定模式的算法。该算法通过建立字符与单词之间的映射关系,确保模式与字符串内容完全匹配。文章详细解释了实现思路与代码逻辑,并通过几个示例验证了其正确性。
1515

被折叠的 条评论
为什么被折叠?



