The syntax of a sentence. This can be easily done using DFA, and it should also be possible to use recursive judgment.
I feel that with dfa, you only need to ensure that the status conversion graph is correct, and basically there will be no bugs, but other methods will be matched.
This type of string similar to a regular expression is prone to many errors.
The DFA definition of Baidu encyclopedia is as follows:
Full name: Deterministic Finite Automaton; Abbreviation: DFA
DFA definition: a definite dfa m is a quintuple: M = (K, Σ, f, S, Z) Where
① K is a rich set. Each element of K is called a state;
② Σ is a rich alphabet. Each element of it is called an input symbol, so Σ is also called an input symbol alphabet;
③ F is a conversion function, which is a ing on K x Σ → K, that is, f (ki, a) = kj, (ki ε K, kj ε K) means,
The current status is ki. If the input is a, it is converted to the next status kj. We call kj a successor status of ki;
④ S * K is the only initial state;
⑤ Z ⊂ K is a set of final states. The final state is also called an acceptable or terminated state.
Status transition diagram of the question:
Now, based on the Status transition diagram, It is very convenient to write a matching simulation Conversion Relationship...
The Code is as follows:
# Include <string>
# Include <vector>
# Include <sstream>
# Include <iostream>
# Include <algorithm>
Using namespace std;
String strNouns [8] =
{
"Tom", "jerry", "goofy", "mickey ",
"Jimmy", "dog", "cat", "mouse"
};
Bool IsNoun (string & str)
{
For (int I = 0; I <8; ++ I)
{
If (str = strNouns [I])
{
Return true;
}
}
Return false;
}
Bool IsVerb (string & str)
{
Return str = "hate" | str = "love"
| Str = "know" | str = "like"
| Str = "hates" | str = "loves"
| Str = "knows" | str = "likes ";
}
Bool IsArticle (string & str)
{
Return str = "a" | str = "";
}
Bool CheckState (vector <string> &)
{
If (vs. empty () return false;
Int nState = 0;
For (int I = 0; I <vs. size (); ++ I)
{
// Printf ("nState: % d, str: % s \ n", nState, vs [I]. c_str ());
Switch (nState)
{
Case 0:
If (IsArticle (vs [I])
{
NState = 1;
Break;
}
Else if (ISN (vs [I])
{
NState = 2;
Break;
}
Else
{
Return false;
}
Case 1:
If (ISN (vs [I])
{
NState = 2;
Break;
}
Else
{
Return false;
}
Case 2:
If (vs [I] = "and ")
{
NState = 0;
Break;
}
Else if (IsVerb (vs [I])
{
NState = 3;
Break;
}
Else
{
Return false;
}
Case 3:
If (IsArticle (vs [I])
{
NState = 4;
Break;
}
Else if (ISN (vs [I])
{
NState = 5;
Break;
}
Else
{
Return false;
}
Case 4:
If (ISN (vs [I])
{
NState = 5;
Break;
}
Else
{
Return false;
}
Case 5:
If (vs [I] = "and ")
{
NState = 3;
Break;
}
Else if (vs [I] = ",")
{
NState = 0;
Break;
}
Else
{
Return false;
}
}
}
Return nState = 5;
}
Int main ()
{
Int nT;
Scanf ("% d % * c", & nT );
While (nT --)
{
Vector <string>;
String line, str;
Getline (cin, line );
Stringstream ss (line );
While (ss> str)
{
Vs. push_back (str );
}
Printf ("% s \ n", CheckState ()? "Yes I will": "no I WON't ");
}
Return 0;
}