3.5 Determine whether the sequence is legal

Topic:
Suppose I and O represent the stacking and popping operations respectively. The initial and final states of the stack are both empty, and the sequence of operations for stacking and popping can be expressed as a sequence consisting of only I and O. The operable sequence is called a legal sequence, otherwise it is called an illegal sequence.
① Which of the sequences shown below are legal?
A. IOIIOIOO B. IOOIOIIO C. IIIOIOIO D. IIIOOIOO
② Through the analysis of ①, write an algorithm to determine whether the given operation sequence is legal. If it is legal, it returns TRUE, otherwise it returns ERROR.

Analysis:
①. A and D are legal sequences; B and C are illegal sequences.
For queue B, it is pushed to the stack once, and then popped twice, because the stack is empty after the first pop and cannot be popped again, which is an error.
For the C queue, there are a total of 5 pushes to the stack and only 3 pops, resulting in the final stack being not empty and an error.
②.
Algorithm idea: push a specified sequence into the stack, every scan to any position needs to check whether the number of times the stack is less than the number of times of the stack (that is, whether the number of O is less than the number of I), if it is greater than that, it is an illegal sequence . After scanning, it is judged whether the stack times are equal to the stack times (that is, whether the number of O is equal to the number of I). If they are not equal, it is an illegal sequence. Otherwise, it is a legal sequence.

Algorithm Description:

Status JudgeSequence(Stack &S){
    
    
	int i=j=k=0;//i表示栈中第i+1个字符,j表示入栈次数;k表示出栈次数
	while(S.data[i]!='\O'){
    
    
		switch(S.data[i]){
    
    
			case 'I':j++;  //入栈次数加1
					 break;
			case 'O':k++;  //出栈次数加1
					 if(k>j){
    
      //比较入栈和出栈次数,若出栈次数大于入栈次数,则是非法序列。
					 	return ERROR;
					 }
					 break;
		}
		i++;
	}
	if(j!=k){
    
      //入栈次数和出栈次数不同
		return ERROR;
	}else{
    
    
		return TRUE;
	}
}

Guess you like

Origin blog.csdn.net/qq_39688282/article/details/108130714