上思路
嵌套两次遍历,判断两边儿单词相等情况是否相等
直接上解法吧
#include<vector>
#include<string>
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string> words;
string temp = "";
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') {
words.push_back(temp);
temp = "";
i++;
}
temp.push_back(s[i]);
if (i == s.size() - 1) {
words.push_back(temp);
}
}
if (words.size() != pattern.size()) return false;
for (int i = 0; i < words.size(); i++) {
for (int j = i+1; j < words.size(); j++) {
if ((pattern[i] == pattern[j]) != (words[i] == words[j]))
return false;
}
}
return true;
}
};
前提是要判断pattern跟s的规模(size)是否相同
思考
虽然做出来了,不过明显感觉时间复杂度有点高
看了一下解法提到了哈希表
ok我要开始狠狠地学数据结构了
—分割线—
哈希表法
2023.11.8
今天去看了一下哈希表的概念,尝试用这个方法写,调试的过程比我上一个解法要慢很多,毕竟刚接触映射。做出来运行时长竟然是0ms
#include<vector>
#include<string>
#include<map>
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string> words;
string temp = "";
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') {
words.push_back(temp);
temp = "";
i++;
}
temp.push_back(s[i]);
if (i == s.size() - 1) {
words.push_back(temp);
}
}
if (words.size() != pattern.size()) return false;
//用哈希表解法
//用双映射关系解决
map<char, string> mp;//A映射到B
map<string, char> rmp;//B映射到A
for (int i = 0; i < words.size(); i++) {
//四种情况
if (!mp.count(pattern[i]) && !rmp.count(words[i] )) {
//A映射不到B,B映射不到A,说明映射表缺,就补表
mp.insert(make_pair(pattern[i], words[i]));
rmp.insert(make_pair(words[i], pattern[i]));
}
else if(mp.count(pattern[i]) && rmp.count(words[i])) {
//A能映射到B,B能映射到A,这时要看双方映射是否全等
if(pattern[i] != rmp.find(words[i])->second
|| words[i]!=mp.find(pattern[i])->second) return false;
}
else {
//单方面能映射到,这时都不需要补表了,可直接判定规律不一致
return false;
}
}
return true;
}
};
在A B都能映射到对方的情况下,我刚开始想的判断规律的算法是
if(pattern[i] != rmp.find( mp.find(pattern[i])->second )->second )
return false;
后来这个解法被例子
“aba” "dog cat cat"打败了