自上而下分析法确定a的位置

自上而下分析法确定a的位置

给出翻译模式,打印出每个a在句子中是第几个字符。(例如当句子是(a,(a,(a,a),(a)),打印结果是2 5 8 10 14。

翻译模式

S’->{S.in=0}S
S->{L.in=S.in+1}(L){S.out=L.out+1}
S->a{S.out=S.in+1;print(S.out)}
L->{L.in=L.in}L1,{S.in=L1.out+1}S{L.out=S.out}
L->{S.in=L.in}S{L.out=S.out}

代码实现

#include <iostream>
#include <cstring>
#include <windows.h>

using namespace std;

int GrammarS(int count, string r);
int GrammarL(int count, string r);

int match(char targe, string r, int location)
{
    if (r[location] == targe)
    {
        return 1;
    }
    return 0;
}

int GrammarS(int count, string r)
{
    if (match('a', r, count))
    {
        cout << count + 1 << " ";
        return count + 1;
    }
    if (match('(', r, count))
    {
        count = GrammarL(count + 1, r);
    }
    if (match(')', r, count))
    {
        return count + 1;
    }
}

int GrammarL(int count, string r)
{
    count = GrammarS(count, r);
    if (match(',', r, count))
    {
        GrammarS(count + 1, r);
    }
}

void check(string r)
{
    cout << "答案应为:";
    int i = 0;
    while (r[i] != '\0')
    {
        if (r[i] == 'a')
        {
            cout << i + 1 << " ";
        }
        i++;
    }
    cout << endl;
}

int main()
{
    string r;
    cin >> r;
    cout << r << endl;
    check(r);
    cout << "采用自上而下分析法所得答案为:";
    GrammarS(0, r);
    cout << endl;
    system("pause");
}
/*样例
(a,(a,a))
((a,a),(a,a))
*/

实现截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值