#ifndef wordpattern_hpp #define wordpattern_hpp #include <iostream> #include <map> #include <vector> #include <sstream> #include <stdio.h> using namespace std; class Solution { public: bool wordPattern(string pattern, string str) { map<char, string> mcs; map<string, char> msc; stringstream ss{str}; string item; for (auto c : pattern) { if(ss>>item){ if(mcs.end() != mcs.find(c)) { if (mcs[c] != item) { return false; } }else{ if(msc.end() != msc.find(item)){ return false; } mcs[c] = item; msc[item] = c; } }else{ return false; } } if(ss>>item) return false; return true; } void test(){ struct wps{ string pat; string str; bool res; }; Solution s; vector<wps> tests{wps{"aaa","cat cat cat",true }, wps{"abba","dog cat cat dog",true}, wps{"abba","dog cat cat fish", false}, wps{"aaaa","dog cat cat dog",false}, wps{"abba","dog dog dog dog",false}, wps{"aaa", "aa aa aa aa", false}}; for (auto t : tests) { cout << "pattern: " << t.pat << ", str: \"" << t.str << "\" "; cout << ((t.res == s.wordPattern(t.pat, t.str)) ? "pass" : "fail") << ‘\n‘; } } }; #endif /* wordpattern_hpp */
程序使用了STL的map和vector,力求简明。
时间: 2024-10-15 20:56:32