leetcode290

来源:互联网 发布:mac装win10连不上wifi 编辑:程序博客网 时间:2024/04/20 21:36

LeetCode290----------Word Pattern

一个map是没办法搞定的,这是我一开始的思路,用一个map来保存char到string的映射,但是通过leetcode的Custom Testcase和单步调试就很容易得到该办法不行的结论。

于是。。。

这道题的关键就在于。。。。

两个map:

一个map用于保存StringToChar的对应关系

一个map用于保存CharToString的对应关系

最后返回的结果必须是两种情况求出来true 或 false 的与。

代码:

class Solution {public:bool wordPattern(string pattern, string str) {map<string, char>strToChar;map<char, string>chToString;vector<string>myVec;stringstream strStream(str);string temp;if (pattern == "" || str == "")return false;/*全部转化为小写*/transform(str.begin(),str.end(),str.begin(),::tolower);transform(pattern.begin(), pattern.end(), pattern.begin(), ::tolower);/*通过stream将string按照空格分割并保存在容器中*/while (strStream >> temp)myVec.push_back(temp);if (myVec.size() != pattern.size())return false;//******************算法开始************************************for (int i = 0; i < pattern.size(); i++){if (chToString.find(pattern[i]) == chToString.end()){chToString[pattern[i]] = myVec[i];//建立字符->string串的map映射}if (strToChar.find(myVec[i]) == strToChar.end()){strToChar[myVec[i]] = pattern[i];//建立string串->字符的map映射}}/*将映射关系按顺序存储在临时变量中*/string result = "";vector<string>resVec;for (int i = 0; i < pattern.size(); i++){result += strToChar[myVec[i]];//将要与pattern匹配的临时变量resVec.push_back(chToString[pattern[i]]);//将要与str匹配的容器}return (result == pattern) && (resVec == myVec);//需要同时满足两个条件}};


0 0