Topic:
The string consists of only three characters a, B, and C, and the string cannot be exactly the same for any consecutive three elements. such as "Acccab" illegal, "ABBCBCA" legal. The number of strings that satisfy the condition with a length of N. It is assumed that no integer overflow is considered, requiring no more time and space complexity than O (N).
Tip: Use dynamic planning, scrolling arrays, matrix exponentiation
#include <iostream>
#include <string>
using namespace std;
int numofstr (const char* str,int len)
{
int *dp=new int[len+1];
dp[0]=0;
dp[1]=3;
if (len==0| | len==1)
return Dp[len];
for (int i=2;i<=len;i++)
{
if (i>2&&str[i-1]==str[i-2]&&str[i-1]==str[i-3])
return-1;
if (Str[i-1]==str[i-2])
dp[i]=2*dp[i-1];
else if (Str[i-1]!=str[i-2])
{
dp[i]=3*dp[i-1];
}
}
return Dp[len];
}
int main ()
{
string str;
while (CIN>>STR)
{
cout<<numofstr (Str.c_str (), Str.size ()) <<endl;
}
return 0;
}