Given a pattern and a string s, find if s 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 s.
Example 1:
Input: pattern = “abba”, s = “dog cat cat dog”
Output: true
Example 2:
Input: pattern = “abba”, s = “dog cat cat fish”
Output: false
Example 3:
Input: pattern = “aaaa”, s = “dog cat cat dog”
Output: false
Example 4:
Input: pattern = “abba”, s = “dog dog dog dog”
Output: false
Constraints:
1 <= pattern.length <= 300
pattern contains only lower-case English letters.
1 <= s.length <= 3000
s contains only lower-case English letters and spaces ’ '.
s does not contain any leading or trailing spaces.
All the words in s are separated by a single space.
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<int> Pattern(26, 0); //记录出现过的小写字母
vector<string> S(26, ""); //与小写字母对应记录对应单词
int size = pattern.size(), sSize = s.size();
int p = 0; //坐标
for (int i = 0; i < size; i++)
{
if (Pattern[pattern[i] - 'a'] == 0) //该小写字母未出现过
{
Pattern[pattern[i] - 'a'] = 1;
while (p < sSize && s[p] != ' ')
{
S[pattern[i] - 'a'].push_back(s[p++]); //记录该小写字母对应的单词
}
for(int j=0;j<26;j++) //查看该小写字母对应的单词是否与其他字母重复
{
if(S[pattern[i]-'a']==S[j]&&(pattern[i]-'a')!=j)
{
return false;
}
}
p++;
}
else //该小写字母已出现过
{
int pp = 0;
while (p < sSize && s[p] != ' ') //判断单词是否对应
{
if (S[pattern[i] - 'a'][pp++] != s[p++])
return false;
}
p++;
}
}
if(p!=sSize+1)return false; //判断是否出现单词多于或少于pattern情况
return true;
}
};
还没学过哈希。明天看看题解