Leetcode 290. Word Pattern | | Leetcode 290. Word Pattern 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution123456789101112131415161718192021222324252627282930313233343536373839class Solution {public: bool wordPattern(string pattern, string str) { vector<string> strs; split(str, strs); if(pattern.size() != strs.size()) { return false; } unordered_map<char, string> m1; unordered_map<string, char> m2; for(int i = 0; i < pattern.length(); i++) { if(m1.find(pattern[i]) == m1.end()) { m1[pattern[i]] = strs[i]; } else if(m1[pattern[i]] != strs[i]) { return false; } if(m2.find(strs[i]) == m2.end()) { m2[strs[i]] = pattern[i]; } else if(m2[strs[i]] != pattern[i]) { return false; } } return true; } private: void split(string& str, vector<string>& strs) { int start = 0; for(int i = 0; i < str.length(); i++) { if(str[i] == ' ') { strs.push_back(str.substr(start, i - start)); start = i + 1; } } strs.push_back(str.substr(start, str.length() - start)); }}; Reference https://leetcode.com/problems/word-pattern/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏