leetcode 290单词规律
作者:互联网
给定一种规律 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
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> words = split(str);
if(pattern.size() != words.size())
return false;
unordered_map<char, string> map1;
unordered_map<string, char> map2;
for(int i = 0 ; i < pattern.size() ; i++)
if(map1.find(pattern[i]) == map1.end()){
if(map2.find(words[i]) != map2.end())
return false;
map1[pattern[i]] = words[i];
map2[words[i]] = pattern[i];
}
else{
string s = map1[pattern[i]];
if(s != words[i])
return false;
}
return true;
}
private:
vector<string> split(const string& s){
vector<string> res;
int start = 0;
for(int i = start + 1 ; i <= s.size() ; )
if(i == s.size() || s[i] == ' '){
res.push_back(s.substr(start, i - start));
start = i + 1;
i = start + 1;
}
else
i ++;
return res;
}
};
标签:false,words,pattern,dog,cat,单词,str,leetcode,290 来源: https://blog.csdn.net/qq_24371789/article/details/91359971