根据下面代码给出基于C#语言的判别是否为LR0文法的private void button2_Clickobject sender EventArgs e函数的完整代码可以适当增添变量定义namespace byyljxfzxt public partial class Form5 Form public Form5 Initia
private void button2_Click(object sender, EventArgs e)
{
string text = richTextBox1.Text;
production = new Dictionary<string, List
Regex.Replace(s, " ", "");
string[] ga = Regex.Split(s, "->");
if (ga.Length != 2) return;
if (ga[0].Length == 0 || ga[1].Length == 0)
return;
if (ga[0].Length != 1 || !char.IsUpper(ga[0][0])) return;
string[] ga2 = Regex.Split(ga[1], "\\|");
if (!production.ContainsKey(ga[0]))
production.Add(ga[0], new List<string>());
foreach (string s1 in ga2)
production[ga[0]].Add(s1);
}
// 判断是否为LR(0)文法
bool isLR0 = true;
foreach (var item in production)
{
string left = item.Key;
List<string> rightList = item.Value;
foreach (string right in rightList)
{
if (right.Length == 1 && char.IsUpper(right[0])) // 形如A->B
{
if (!production.ContainsKey(right))
{
isLR0 = false;
break;
}
}
else if (right.Length > 1) // 形如A->aB或A->a
{
for (int i = 0; i < right.Length - 1; i++)
{
if (char.IsUpper(right[i]) && !char.IsUpper(right[i + 1])) // 形如A->aB
{
string beta = right.Substring(i + 1);
foreach (string s in rightList)
{
if (s.Length == beta.Length && s.StartsWith(beta))
{
isLR0 = false;
break;
}
}
}
}
}
if (!isLR0) break;
}
if (!isLR0) break;
}
if (isLR0)
MessageBox.Show("该文法是LR(0)文法");
else
MessageBox.Show("该文法不是LR(0)文法");
原文地址: https://www.cveoy.top/t/topic/hc8m 著作权归作者所有。请勿转载和采集!