思路:
1.首先要分割字符串,所以我单独写了个函数
vector<string> cut_str(string str,char c)
{
vector<string> array_string;
int flag = 0;
for (int i = 0;i<=str.length();i++)
{
if (str[i]==c)
{
array_string.push_back(str.substr(flag,i-flag));
flag = i + 1;
}
if (i==str.length()&&flag!=str.length())
{
array_string.push_back(str.substr(flag,i-flag));
}
}
return array_string;
}
其中:substr很关键
2.利用双映射来进行匹配判断:map<char, string> mp1; map<string, char> mp2; 为什么要用双映射呢?如下图
具体代码:
vector<string> cut_str(string str,char c)
{
vector<string> array_string;
int flag = 0;
for (int i = 0;i<=str.length();i++)
{
if (str[i]==c)
{
//cout<<str.substr(flag,i-flag)<<endl;
array_string.push_back(str.substr(flag,i-flag));
flag = i + 1;
}
if (i==str.length()&&flag!=str.length())
{
//cout<<str.substr(flag,i-flag)<<endl;
array_string.push_back(str.substr(flag,i-flag));
}
}
return array_string;
}
bool wordPattern(string pattern, string str) {
vector<string> array_str = cut_str(str,' ');
if (pattern.length()!=array_str.size())
{
return false;
}
map<char, string> mp1;
map<string, char> mp2;
for(int i = 0; i < pattern.size(); i ++) {
map<char, string>::iterator mp1Ite;
map<string, char>::iterator mp2Ite;
mp1Ite = mp1.find(pattern[i]);
mp2Ite = mp2.find(array_str[i]);
if(mp1Ite == mp1.end() && mp2Ite == mp2.end()) {
//如果没有,则填进去,并形成双映射关系
mp1[pattern[i]] = array_str[i];
mp2[array_str[i]] = pattern[i];
}
else if(mp1Ite != mp1.end() && mp2Ite != mp2.end()) {
//只有两种映射都匹配才会成功
if(mp1[pattern[i]] != array_str[i] || mp2[array_str[i]] != pattern[i])
return false;
}
else return false;
}
return true;
}
主要考查对字符串和STL的基本用法。