判断出栈序列的正误

声明:将入栈序列中位置在较前面的元素称为较小的元素,位置较靠后的元素称为较大的元素

由此列出一条关于出栈序列中元素的性质:任意认定出栈序列中的一个元素,在此元素位置之后(按出栈序列来看位置先后)的比此元素小的全体元素按由大到小进行排列(即逆序排列)

算法核心解读:

1.将元素在入栈序列中进行编号(由小到大)

2.按照上述性质在出栈序列中逐元素地进行检验,若有元素不满足上述性质则此出栈序列不存在,反之,则存在。

"""对出栈序列正误的判断//Judging the correctness of a stack popping sequence"""
#子函数:用来确定某元素对应在入栈序列中的编号
def find_number(stack_in_sequence,element):
    for i in range(len(stack_in_sequence)):
        if stack_in_sequence[i]==element:
            return i
    return -1
#输入入栈序列(有i个元素)//Input the stack pushing sequence (with i elements)
print('Please enter the stack sequence and use "over" as the identifier to end the input:')
stack_in_sequence=[]
i=0#用i来标记栈中有多少个元素//How many elements are in the stack
while(1):
    a=input()
    if a=="over":
        break
    else:
        stack_in_sequence.append(a)
        i+=1
#输入需要判断的指定序列//Input the specified sequence to be judged
print('Please enter the stack popping sequence and use "over" as the identifier to end the input:')
stack_out_number_sequence=[]
stack_out_sequence=[]
for j in range(0,i):
     stack_out_sequence.append(input())
     if find_number(stack_in_sequence,stack_in_sequence[j])==-1:
         print('The sequence is wrong!')
         exit(0)
     stack_out_number_sequence.append(find_number(stack_in_sequence,stack_in_sequence[j]))
#从指定序列的第1个元素开始做循环判断到第i-1个元素(即可)//Start a loop to judge from the first element of the specified sequence up to the (i-1)th element.
p=0#用来判断(以单个元素为起点开始做循环时)是否出现可以否定此序列的判定点,p==0时无,p==1时是
for k in range(0,i):
     m=stack_out_number_sequence[k]
     for l in range(k+1,i):#判断在第l个元素之后小于此元素的元素是否相对于入栈顺序互逆,若是i++,若否跳出循环,判定为非出栈序列
                           #//Check if the elements smaller than the ith element, after it, are in the reverse order compared to the stack pushing order.
                           #If yes, increment i. If no, exit the loop and judge it as a non-stack popping sequence.
        if stack_out_number_sequence[l]

你可能感兴趣的:(数据结构)