1.文法
1)E->E+T
2)E->E-T
3)E->T
4)T->T*F
5)T->T/F
6)T->F
7)F->i
8)F->(E)
2.去左递归、提取左因子后的改写文法
1) E -> TE'
2) E'-> +TE' | -TE' | e
3) T -> FT'
3) T'-> *FT' | /FT' | e
4) F -> int | (E)
3. 代码
class Exp {
private:
string s;
int i;
enum Token { PLUS, MINUS, TIME, DIVIDE, OPEN, CLOSE, INT };
map<Token, char> op;
bool E() {
return T() && EA();
}
bool EA() {
int save = i;
if (term(PLUS)) return T() && EA();
i = save;
if (term(MINUS)) return T() && EA();
i = save;
return true;
}
bool T() {
return F() && TA();
}
bool TA() {
int save = i;
if (term(TIME)) return F() && TA();
i = save;
if (term(DIVIDE)) return F() &&TA();
i = save;
return true;
}
bool F() {
int save = i;
if (term(INT)) return true;
i = save;
return term(OPEN) && E() && term(CLOSE);
}
bool term(Token t) {
if (i == s.size()) return false;
if (t < INT) return (s[i++] == op[t]);
int save = i;
for (; i < s.size() && isdigit(s[i]); ++i);
return i > save;
}
public:
bool valid;
Exp(string exp) : s(exp), i(0), valid(false), op({ { PLUS, '+' }, { MINUS, '-' }, { TIME, '*' }, { DIVIDE, '/' }, { OPEN, '(' }, { CLOSE, ')' } }) {
valid = E() && (i == s.size());
}
};