Aim: Write a program to check wether a string belongs to the grammer or not.

 

#include <iostream>

using namespace std;

bool checkGrammar1(string str) {
    if (str[0] != 'a' || str[str.length() - 1] != 'b') {
        return false;
    }
    for (int i = 1; i < str.length(); i++) {
        if (str[i - 1] == 'b' && str[i] == 'a') {
            return false;
        }
    }
    return true;
}

bool checkGrammar2(string str) {
    int n = str.length();
    if (n % 2 == 0) {
        return false;
    }
    for (int i = 0; i < n / 2; i++) {
        if ((str[i] != 'a' && str[i] != 'b') || (str[n - 1 - i] != 'a' && str[n - 1 - i] != 'b')) {
            return false;
        }
        if (str[i] != str[n - 1 - i]) {
            return false;
        }
    }
    return true;
}

bool checkGrammar3(string str) {
    int n = str.length();
    int cntA = 1, cntB = 0;
    if (n == 0) {
        return false;
    }
    if (str[0] != 'a' || str[n - 1] != 'b') {
        return false;
    }
    for (int i = 1; i < str.length(); i++) {
        if (str[i] == 'a') {
            cntA++;
        } else if (str[i] == 'b') {
            cntB++;
        } else {
            return false;
        }
        if (str[i - 1] == 'b' && str[i] == 'a') {
            return false;
        }
    }
    if (cntA * 2 != cntB) {
        return false;
    }
    return true;
}

string p(bool flag) {
    if (flag) {
        return "true";
    } else {
        return "false";
    }
}

int main() {
    cout << "1. Grammar 1  2. Grammar 2" << endl;
    cout << "3. Grammar 3  4. End" << endl;
    string s;
    int n;
    cout << "Enter Choice: ";
    cin >> n;
    while (n != 4) {
        cout << "Enter String: ";
        cin >> s;
        if (n == 1) cout << "Checking for grammar 1: " << p(checkGrammar1(s)) << endl;
        if (n == 2) cout << "Checking for grammar 2: " << p(checkGrammar2(s)) << endl;
        if (n == 3) cout << "Checking for grammar 3: " << p(checkGrammar3(s)) << endl;
        cout << "Enter Choice: ";
        cin >> n;
    }
    return 0;
}







Comments

Popular posts from this blog

Write a program to find out the FIRST of the Non‐terminals in a grammar.