题目
给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false
示例 4:
输入: pattern = "abba", str = "dog dog dog dog"
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
我的方法
思路
代码
static set<string> existWord;
bool getWord(char *&wp, string &str)
{
while (*wp != '\0' && *wp != ' ')
str.push_back(*wp++);
if (str.empty()) return false;
if (existWord.count(str)) return false;
existWord.insert(str);
if (*wp == ' ') ++wp;
return true;
}
bool checkWord(char *&wp, const string& sour)
{
int lenwp = strlen(wp);
if (lenwp < sour.size()) return false;
if (lenwp == sour.size())
{
if (strcmp(wp, sour.c_str())) return false;
wp += sour.size();
return true;
}
for (auto c : sour + " ")
{
if (*wp++ != c) return false;
}
return true;
}
class Solution
{
public:
Solution()
{
// 力扣的判题机在读取代码后,对每个测试用例,都会初始化一次类,但全局变量和类内静态变量需要手动初始化。
existWord.clear();
}
public:
bool wordPattern(string pattern, string s)
{
vector<string> strs(123);
char* wp = const_cast<char*>(s.c_str());
for (auto c : pattern)
{
if (strs[c].empty())
{
if (!getWord(wp, strs[c]))
return false;
}
else
{
if (!checkWord(wp, strs[c]))
return false;
}
}
return *wp == '\0';
}
};