Lexical Analyzer

Alex has recently decided to learn about how to design compilers. As a first step, he needs to find the number of different variables that are present in the given code.

So Alex will be provided N statements each of which will be terminated by a semicolon(;). Now Alex needs to find the number of different variable names that are being present in the given statement. Any string which is present before the assignment operator denotes a variable name.

Example:

Input:  n = 2, v = {"foo = 3;","bar = 4;"}
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int lexicalAnalyzer(int nvector<string&v)
{
    set<stringst;
    for (int i = 0i < ni++)
    {
        string x = "";
        for (int j = 0j < v[i].size(); j++)
        {
            if (v[i][j] != '=' && v[i][j] != ' ')
            {
                x += v[i][j];
            }
            if (v[i][j] == '=')
            {
                st.insert(x);
            }
        }
    }
    return st.size();
}
int main()
{
    int n = 2;
    vector<stringv = {"foo = 3;""bar = 4;"};

    cout << lexicalAnalyzer(nv<< "\n";
    return 0;
}


No comments:

Post a Comment