问题
思路
直接比两个模式没法直接比,所以我的办法是,肯定要把他们统一到同一种编码来进行比较。
代码
class Solution {
public:
bool wordPattern(string pattern, string str) {
std::vector<std::string> ret;
std::stringstream ss;
ss << str;
std::string t;
while(ss >> t ){
ret.push_back(t);
}
int sz1 = pattern.size();
int sz2 = ret.size();
if(sz1 != sz2) return false;
std::map<char, int> mapper_pattern;
std::map<std::string, int> mapper_str;
int total1 = 0;
int total2 = 0;
int cur1 = 0;
int cur2 = 0;
for(int i = 0; i < sz1; ++i){
if( mapper_pattern.find(pattern[i]) == mapper_pattern.end() ) mapper_pattern[pattern[i]] = ++total1;
cur1 = mapper_pattern[ pattern[i] ];
if( mapper_str.find( ret[i] ) == mapper_str.end() ) mapper_str[ret[i]] = ++total2;
cur2 = mapper_str[ ret[i] ];
if( cur1 != cur2 ) return false;
}
return true;
}
};