# 面试题 16.18

To Index ---

## 面试题 16.18

`````````

0 <= len(pattern) <= 1000
0 <= len(value) <= 1000

`````````

`````````
class Solution {
string pattern;
inline string patternString(string a, string b)
{
string res;
for(auto c: pattern)
{
if(c=='a') res+=a;
else res+=b;
}
return res;
}
public:
bool patternMatching(string pattern, string value) {

int sizeA=0;
int sizeB=0;

if(pattern[0]=='b')
{
string tmp;
for(auto c:pattern)
tmp+= c=='a' ? 'b' :'a';
this->pattern=tmp;
}
else
this->pattern=pattern;

for(auto c:this->pattern)
{
if(c=='a') sizeA++;
else sizeB++;
}

if(sizeA ==0 && sizeB ==0) return value=="";
if(sizeA==0)
{
int cntB=value.length()/sizeB;
return patternString("",value.substr(0,cntB)) ==value;
}
if(sizeB==0)
{
int cntA=value.length()/sizeA;
return patternString(value.substr(0,cntA),"") ==value;
}
int startB=0;
for(auto c:this->pattern)
{
if(c=='a') {
startB++;
}
else
break;
}
//cout<<startB<<endl;
//cout<<sizeA<<endl;
int cntA=value.length()/sizeA;
//     cout<<cntA<<endl;
for(int i=0; i<=cntA;i++)
{
int cntB=(value.length()-sizeA*i)/sizeB;

string a=value.substr(0,i);
//      cout<<i*startB<<endl;
string b =value.substr(i*startB,cntB);
//       cout<<a<<"  "<<b<<endl;
if(a==b) continue;
//    cout<<patternString(a,b) <<endl;
if(patternString(a,b) == value) return true;

}
return false;
}
};``````
``````> 执行用时 :4 ms, 在所有 C++ 提交中击败了63.82%的用户

Last updated