题目描述:
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.
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.
要完成的函数:
bool wordPattern(string pattern, string str)
说明:
1、这道题目是之前char-char的升级版,现在是char-string。要求不变,仍然是不能两个相同的字母对应一个string,不能两个相同的string对应一个字母。仿照之前思路,很容易构造出代码。
2、这道题目还要注意有可能pattern里面的字母个数和string里面的单词个数不匹配,边界条件处理一下就好了。
代码如下:
bool wordPattern(string pattern, string str)
{
map<char,string>m1;
map<string,char>m2;
int j=0;
string str1="";//存储str中切分出来的单词
for(int i=0;i<pattern.size();i++)
{
str1="";
if(j>str.size())//如果pattern的字母多于str中的单词
return false;
while(str[j]!=' '&&str[j]!='