Data structures 形式语言:检查一个堆栈和一个队列的语言
编写方法Data structures 形式语言:检查一个堆栈和一个队列的语言,data-structures,stack,queue,Data Structures,Stack,Queue,编写方法isL(w)的伪代码,该方法仅使用1个堆栈和1个队列检查字符串w是否是L的元素 L={a^n⋅b^n⋅c^m⋅d^m|n≥1米≥1} U{a^n⋅b^m⋅c^m⋅d^n | n≥1米≥1} (a^n是a的n次方) 您可以假设堆栈和队列已经实现,并将它们与变量stack和queue一起使用 我的代码只回答了这个问题的一半: isL(w) { for (each char ch in w) { if (ch == 'a' || ch == 'c') {
isL(w)
的伪代码,该方法仅使用1个堆栈和1个队列检查字符串w
是否是L的元素
L={a^n⋅b^n⋅c^m⋅d^m|n≥1米≥1} U{a^n⋅b^m⋅c^m⋅d^n | n≥1米≥1}
(a^n是a的n次方)
您可以假设堆栈和队列已经实现,并将它们与变量stack
和queue
一起使用
我的代码只回答了这个问题的一半:
isL(w) {
for (each char ch in w) {
if (ch == 'a' || ch == 'c') {
stack.push( ch );
}
else if (ch == 'b' || ch == 'd') {
queue.enqueue( ch );
}
else return false; // no other letter than a,b,c,d
}
while (!queue.isEmpty()) {
if (stack.pop() == 'c' && queue.dequeue() == 'b')
continue;
else if (stack.pop() == 'a' && queue.dequeue() == 'd')
continue;
else
return false;
}
return true;
}
虽然我的目标是后一个子集,但后一个子集也是错误的
如何实现同时检查前一个子集的完整答案
isL(w) {
if (w[0] != 'a') return false
stack.push('a')
for ch in w{
if (!stack.isEmpty()) {
if (ch == 'a') stack.push(ch)
else if (ch == 'b') stack.pop()
else return false
}
else {
if (ch == 'c') queue.push(ch)
else if (!queue.isEmpty() && ch == 'd') queue.dequeue()
else return false
}
}
return true
}