Given a pattern
and a string str
, find if str
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern
and a non-empty word in str
.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false. - 题解:首先我自己想的思路是先设计两个multimap,分别存放两个一一关系。然后遍历找出相同key值的元素,检查其value值是否相等。结果发现当出现类似于 pattern=="abc",str="a b c",输出false,有误。使用的函数是
- // Find all values by key using equal_range()
- 46
typedef AuthorBooks::iterator iterAB;
- 47
pair<iterAB, iterAB> pos = authorBooks.equal_range(searchItem);
48while(pos.first != pos.second)
49cout << pos.first++->second << endl;
- 后来参考使用的思路是:设计两个map,分别存放一一对应关系,然后插入到map中去,再遇到相同的key值时,查看其value是否相同,如果不同,则返回false。
- 首先整理下字符串分割的知识:
- strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串中包含的所有字符。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针。
- 给定一个字符串 str="cat dog dog cat",如何将它们切割成四个字符串,使用的代码如下:
char* split = " "; char* p; char* c; const int len = str.length(); c = new char[len + 1]; strcpy(c,str.c_str()); p = strtok(c, split); while (p != NULL){ vec.push_back(p); p = strtok(NULL, split); }
代码如下:<pre name="code" class="cpp">class Solution { public: bool wordPattern(string pattern, string str) { typedef unordered_map<char, string> Mapchar1; typedef unordered_map<string,char> Mapchar2; Mapchar1 mapchar1; Mapchar2 mapchar2; vector<string> vec; //"abba" "dog cat cat dog" char* split = " "; char* p; int i = 0; char* c; char*d; const int len = str.length(); c = new char[len + 1]; strcpy(c,str.c_str()); p = strtok(c, split); while (p != NULL){ vec.push_back(p); /*mapchar1.insert(map<string, char>::value_type(p, pattern[i])); mapchar2.insert(map<char,string>::value_type(pattern[i],p));*/ i++; p = strtok(NULL, split); } if(i!=pattern.length()) return false; for (i = 0; i < pattern.length(); i++){ if (mapchar1.find(pattern[i]) == mapchar1.end() && mapchar2.find(vec[i]) == mapchar2.end()){ mapchar1.insert(make_pair(pattern[i],vec[i])); mapchar2.insert(make_pair(vec[i],pattern[i])); } else if (mapchar1[pattern[i]] != vec[i] || mapchar2[vec[i]] != pattern[i]) return false; } return true; } };