290. Word Pattern

xiaoxiao2021-02-28  44

第一步对字符串进行单词识别分割,存储在动态数组内;

其次建立pattern和str单词序列之间的正向和逆向映射表,如果满足正向和逆向的一一对应关系,那么就符合标准。

class Solution { public: bool wordPattern(string pattern, string str) { vector<string> list; //store words; for(int i=0,j=0;i<str.length()&&j<str.length();i++) { if(str[i]==' ') { list.push_back(str.substr(j,i-j)); j=i+1; } if(i==str.length()-1) list.push_back(str.substr(j,str.length()-j)); } if(list.size()!=pattern.length()) return 0; unordered_map<char,string> table; //pattern to str unordered_map<string,char> res; //str to pattern for(int i=0;i<pattern.length()&&i<list.size();i++) { if(table.find(pattern[i])==table.end()&&res.find(list[i])==res.end()) //all not find element ,then add these into the map { table[pattern[i]]=list[i]; res[list[i]]=pattern[i]; } else { if(table[pattern[i]]!=list[i]||res[list[i]]!=pattern[i]) return 0; } } return 1; } };

 

转载请注明原文地址: https://www.6miu.com/read-2633000.html

最新回复(0)