hoj 1110 Simply Syntax // poj 1126 Simply Syntax

/*

题目:

    该文符合以下三条语法为正确:

    1.单一的单词p到z,大写字母:N, C, D, E, I

    2.如果字符串s书写正确,则Ns同样正确。

    3.若字符串s,t正确的话,则Cst, Dst, Est, and Ist同样正确

分析:

    递归字符串即可。若当前的字符串的长度为1,符合语法1的话,返回正确。若长度大于1的话,

    若当前首字母为N,递归从第二位开始的该字符串,若成功,返回成功。当首字母为C, D, E, I,

    若字符串能够分成三个部分X(C, D, E, I),s,t的话,返回成功。

    分解字符串的函数可以用string中的substr函数,比如:

    s = "12345"

    s.substr(1) = "2345";

    s.substr(2) = "345";

*/

#include <iostream>

#include <string>

#include <cstdio>

using namespace std;

bool dfs(string s)

{

    int len = s.size();

    if(len==1)

    {

        if((s[0]>='p'&&s[0]<='z')||s[0]=='N'||s[0]=='C'||s[0]=='D'||s[0]=='E'||s[0]=='I')

            return true;

        else

            return false;

    }

    if(s[0]=='N')

    {

        if(dfs(s.substr(1)))

            return true;

        else

            return false;

    }

    if(s[0]=='C'||s[0]=='D'||s[0]=='E'||s[0]=='I')

    {

        if(len==2)

            return false;

        string temp;

        for(int i=0;i<len-1;i++)

        {

            temp = temp+s[i];

            if(dfs(temp.substr(1))&&dfs(s.substr(i+1)))

                return true;

        }

    }

    return false;

}

int main()

{

    freopen("sum.in","r",stdin);

    freopen("sum.out","w",stdout);

    string s;

    while(cin>>s)

    {

        if(dfs(s))

            printf("YES\n");

        else

            printf("NO\n");

    }

    return 0;

}

原文地址:https://www.cnblogs.com/yejinru/p/2477969.html