输出: false
示例 3:
输入: pattern = “aaaa”, str = “dog cat cat dog”
输出: false
示例 4:
输入: pattern = “abba”, str = “dog dog dog dog”
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
以下用了map,字母作为键值与相对应的单词为一对存入map中,如已有这个键值,看两个value是否相等,排除了key一样但value不同,如没有,则存入,程序下半段,用了set容器,set可以自动去重,排除了key不同但value一样的情形
class Solution {
public:
bool wordPattern(string pattern, string str) {
if(pattern == "" || str.length() == 0)
return false;
map<char,string> res;
set<string> s;
int index1 = 0;
int index2 = -1;
int sum = 0;
for(int i = 0; i<pattern.length();i++){
if(index2 == -1)
sum++;
if(sum == 2)
return false;
index1 = index2+1;
index2 = str.find(' ',index1);//find用法需牢记
string tem = str.substr(index1,index2-index1);//substr用法需牢记
if(res.find(pattern[i]) != res.end())
{
if(res[pattern[i]] != tem)
return false;
}
else
{
res[pattern[i]] = tem;
}
}
if(index2 != -1)
return false;
for(map<char,string>::iterator iter = res.begin();iter != res.end();iter++)
{
s.insert(iter->second);
}
if(s.size() != res.size())
return false;
return true;
}
};