String legitimacy length

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.