leetcode290. 單詞模式
阿新 • • 發佈:2018-12-18
給定一種 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
建立兩個雜湊表,雙向對應
#include<iostream> #include<unordered_map> #include<string> using namespace std; 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.count(pattern[i])>0 && map1[pattern[i]] != words[i]) return false; if (map2.count(words[i]) > 0 && map2[words[i]] != pattern[i]) return false; map1[pattern[i]] = words[i]; map2[words[i]] = pattern[i]; } return true; } vector<string> split(const string& str) { vector<string> res; string temp; for (int i = 0; i <= str.size(); i++) { if (str[i] == ' ' || str[i] == '\0') { res.push_back(temp); temp.clear(); } else { temp += str[i]; } } return res; } }; int main() { string pattern = "abba"; string str = "cat dog dog cat"; bool reslut = Solution().wordPattern(pattern, str); if (reslut) { cout << "true"; } else { cout << "false"; } system("pause"); return 0; }