给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = "abba", s = "dog cat cat dog" 输出: true
示例 2:
输入: pattern = "abba", s = "dog cat cat fish" 输出: false
示例 3:
输入: pattern = "aaaa", s = "dog cat cat dog" 输出: false
- #include
- #include
- #include
- using namespace std;
-
- /*
- * 单词规律的判断,和同构字符串相似
- * 使用两个无序哈希表保存映射关系
- * 设置一个临时变量保存单词
- * 如果单词和字符有之间映射关系但是值不同,返回false
- */
- bool wordPattern(string pattern, string s) {
- unordered_map
char> s2c; - unordered_map<char, string> c2s;
- int len = s.size();
- int i = 0;
- for (auto c : pattern) {
- if (i >= len) {
- return false;
- }
- int j = i;
- while (j < len && s[j] != ' ') j++;
- const string& tmp = s.substr(i, j - i);
- if (s2c.count(tmp) && s2c[tmp] != c || c2s.count(c) && c2s[c] != tmp) {
- return false;
- }
- s2c[tmp] = c;
- c2s[c] = tmp;
- i = j + 1;
- }
- return true;
- }
- int main() {
- string pattern = "abba";
- string s = "dog cat cat dog";
- bool ans = wordPattern(pattern, s);
- cout << boolalpha << ans << endl;
- return 0;
- }
单词规律的判断,和同构字符串相似,使用两个无序哈希表保存映射关系,设置一个临时变量保存单词,如果单词和字符有之间映射关系但是值不同,返回 false。
subsrt(pos, len) 函数表示从 pos开始 拷贝 len 个字符。