- 单词规律
给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = “abba”, s = “dog cat cat dog”
输出: true
示例 2:
输入:pattern = “abba”, s = “dog cat cat fish”
输出: false
class Solution {
public:
bool wordPattern(string pattern, string s) {
stringstream ss(s);
vector<string> vecS;
string inputStr;
while(getline(ss, inputStr, ' ')) {
vecS.push_back(inputStr);
}
if(pattern.size() != vecS.size()) {
return false;
}
map<char, string> mapP;
map<string, int> mapCnt;
for(int i = 0; i < pattern.size(); i++) {
if(mapP.count(pattern[i])) {
if(mapP[pattern[i]] != vecS[i]) {
return false;
}
} else {
mapP[pattern[i]] = vecS[i];
++mapCnt[vecS[i]];
if(mapCnt[vecS[i]] > 1) {
return false;
}
}
}
return true;
}
};