mobile wallpaper 1
mobile wallpaper 2
mobile wallpaper 3
mobile wallpaper 4
134 字
1 分钟
LeetCode 面试经典150题 [40/150 单词规律]
2024-06-26

题目描述#

给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。 示例 1:

输入: pattern = "abba", s = "dog cat cat dog"
输出: true

示例 2:

输入:pattern = "abba", s = "dog cat cat fish"
输出: false

个人C++解答#

和上道题一样,反正都是O(n),就没必要创两个哈希表了,虽然好看,但是还是比较浪费内存的

class Solution {
public:
bool wordPattern(string pattern, string s) {
string Map[26];
fill(Map, Map + 26, string(" "));
int index_l = 0, index_r = 0;
for (int i = 0; i < pattern.size(); i++) {
if(index_r == s.size()) return false;
s = s.substr(index_l, s.size());
index_r = s.find(' ') != string::npos ? s.find(' ') : s.size();
string str_com = s.substr(0, index_r);
for (int j = 0; j < 26; j++) {
if (Map[j].compare(str_com) == 0 && j != pattern[i] - 'a') {
return false;
}
}
if (Map[pattern[i] - 'a'] == " ") {
Map[pattern[i] - 'a'] = str_com;
} else if (Map[pattern[i] - 'a'].compare(str_com) == 0) {
} else {
return false;
}
index_l = index_r + 1;
}
if(index_r!=s.size()) return false;
return true;
}
};
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode 面试经典150题 [40/150 单词规律]
https://ericonline.cn/posts/leetcode-面试经典150题-40-150-单词规律/
作者
Eric
发布于
2024-06-26
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录