Judgment based stack operable

 

description

 

Suppose I and O represent the pushing and popping operations. Stack beginning and final states are empty. Push and stack operation sequence can be expressed as a sequence only by the I and O's, said the operational sequence as legitimate sequence, otherwise known as illegal sequences. Please design an algorithm to determine the sequence of operations to legality. If the legal output "true", and vice versa output "false".

Entry

 

A plurality of sets of data, each set of operation sequence data line of indefinite length A. When A is "0", the input end.

Export

 

Output data corresponding to each row. If the sequence is a valid sequence output A "TRUE", on the contrary output "FALSE".

Sample input 1 

ioioio
IIOOOO
0

Sample Output 1

TRUE
FALSE
#include <iostream>
using namespace std;


int Judge(char str[]){
	int i=0;
	int jI;//入栈操作的次数
	int kO;//出栈操作的次数
	jI=kO=0;
	while(str[i]!='\0')
	{
		switch(str[i]){
			case 'I':
				jI++;
				break;
			case 'O'://当遇到出栈操作时,要判断这个状态下入栈的次数是否大于
						//出栈的次数 
				kO++;
				if(kO>jI)
				{
					printf("FALSE\n");
					return 0;
				}
				break; 
		}
		i++;
	}
	//无论出栈还是入栈,指针都要后移 
	if(jI==kO)
	{
			printf("TRUE\n");
			return 1;
	}
	else
	{
			printf("FALSE\n");
			return 0;
	}
}


int main()
{
	string str;
	while(1)
	{	 
		cin>>str;
		if(str=="0")return 0;
		Judge(&str[0]);
	}
	return 0;
}

 

Published 100 original articles · won praise 4 · Views 3687

Guess you like

Origin blog.csdn.net/weixin_43673589/article/details/104391886
Recommended