290. 单词规律
1 class Solution 2 { 3 vector<string> res; 4 void spilt(string s,char c,vector<string> &res) 5 { 6 istringstream iss(s); 7 string temp; 8 while(getline(iss,temp,c)) 9 { 10 //如果temp不为空,才可以添加进去 11 if(!temp.empty()) res.push_back(temp); 12 } 13 } 14 public: 15 bool wordPattern(string pattern, string str) 16 { 17 spilt(str,' ',res); 18 unordered_set<string> u; 19 if(pattern.size() != res.size()) return false; 20 unordered_map<char,string> hash; 21 for(int i = 0;i < pattern.size();i ++) 22 { 23 if(hash.count(pattern[i]) && hash[pattern[i]] != res[i]) return false; 24 if(hash.count(pattern[i]) == 0 && u.find(res[i]) != u.end()) return false; 25 hash[pattern[i]] = res[i]; 26 u.insert(res[i]); 27 } 28 return true; 29 } 30 };
Mamba never out

浙公网安备 33010602011771号