Data structure: Lituo OJ questions (one practice per day)

Question 1: Valid Parentheses

Given a   string  that contains only '(', ')', '{', '}', '[',  determine whether the string is valid.']'s

A valid string must satisfy:

  1. An opening parenthesis must be closed with a closing parenthesis of the same type.
  2. Opening parentheses must be closed in the correct order.
  3. Each closing parenthesis has a corresponding opening parenthesis of the same type.
  4. Example 2:

    Input: s = "()[]{}"
     Output: true

Idea one:

        Step 1: Write out the structure of the array stack , and then write out the functions of stack initialization, stack pushing, stack popping, getting the top element of the stack, destroying the stack, and checking whether the stack is empty ;

        Step 2: Create a structure variable, initialize it , while(*s) decides whether to continue the loop, use switch to find the corresponding pre-symbols and push them onto the stack, if it is a post-symbol , first judge whether ps is empty , Then judge whether there is a corresponding pre-conformity, if there is no : end directly, if there is : continue to loop;

        Step 3: Create the corresponding bool variable to record the return value of the SLEmpty() function, and destroy the creation space.

Note: The OJ question will not judge the code to open up the dynamic memory space, so in the OJ question, it is correct not to destroy the opened dynamic memory.

//约定类型方便更改类型
typedef char STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}SL;
//初始化
void SLInit(SL* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

//入栈
void SLPush(SL* ps, STDataType x)
{
	assert(ps);
	//栈顶=容量说明需要扩容
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->capacity = newcapacity;
		ps->a = tmp;
	}
	ps->a[ps->top] = x;
	//后缀++方便下一次入栈和打印栈顶
	ps->top++;
}

//出栈
void SLPop(SL* ps)
{
	assert(ps);
	//为空情况“0”
	assert(ps->top > 0);
	//
	--ps->top;
}


//获得栈顶元素
STDataType SLTTop(SL* ps)
{
	assert(ps);
	//为空情况“0”
	assert(ps->top > 0);
	int n = (ps->top) - 1;
	return ps->a[n];
}


//获取栈中有效元素个数
int SLSize(SL* ps)
{
	assert(ps);
	return ps->top;
}

//销毁栈
void SLDestroy(SL* ps)
{
	assert(ps);
	//开辟数组优势:一次全部释放
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool SLEmpty(SL* ps)
{
	assert(ps);
	//为“0”说明为NULL
	if (ps->top == 0)
	{
		return true;
	}
	return false;
}


//思路一:使用switch
bool isValid(char * s)
{
	SL ps;
	char val;
	//初始化
	SLInit(&ps);
	while (*s)
	{
		switch (*s)
		{
		case '(':
		case '[':
		case '{':
				//入栈
				SLPush(&ps, *s);
				break;
		case ')':
		case '}':
		case ']':
				//判断栈是否为空
				if (SLEmpty(&ps))
				{
					//销毁开辟的动态内存
					SLDestroy(&ps);
						return false;
				}
				//栈顶值
				val = SLTTop(&ps);
				//出栈
				SLPop(&ps);
				if (*s == ')' && val != '(' ||
						*s == ']' && val != '[' ||
						*s == '}' && val != '{')
				{
						SLDestroy(&ps);
						return false;
				}
				break;
		}
		s++;
	}
	bool ret = SLEmpty(&ps);
	SLDestroy(&ps);
	return ret;
}

Improved simplification:

        The principle is the same as above, and the content to be realized is the same as above, but the multiple calls caused by the switch() statement and the increase in steps are simplified. After using the if----else statement , the code is more concise and clear , and there is no need to consider every The operation , if all solved at once. Overall, the amount of code is reduced by one-third .

//约定类型方便更改类型
typedef char STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}SL;
//初始化
void SLInit(SL* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

//入栈
void SLPush(SL* ps, STDataType x)
{
	assert(ps);
	//栈顶=容量说明需要扩容
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->capacity = newcapacity;
		ps->a = tmp;
	}
	ps->a[ps->top] = x;
	//后缀++方便下一次入栈和打印栈顶
	ps->top++;
}

//出栈
void SLPop(SL* ps)
{
	assert(ps);
	//为空情况“0”
	assert(ps->top > 0);
	//
	--ps->top;
}


//获得栈顶元素
STDataType SLTTop(SL* ps)
{
	assert(ps);
	//为空情况“0”
	assert(ps->top > 0);
	int n = (ps->top) - 1;
	return ps->a[n];
}


//销毁栈
void SLDestroy(SL* ps)
{
	assert(ps);
	//开辟数组优势:一次全部释放
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool SLEmpty(SL* ps)
{
	assert(ps);
	//为“0”说明为NULL
	if (ps->top == 0)
	{
		return true;
	}
	return false;
}


//改进简化内容if——else
bool isValid(char * s)
{
	SL ps;
	char val;
	//初始化
	SLInit(&ps);
	while (*s)
	{
	     if(*s == '(' || *s == '{' || *s == '[')
		{
		    //入栈
		    SLPush(&ps, *s);
		}
		else
		{
					//判断栈是否为空
		    if (SLEmpty(&ps))
		    {
			//销毁开辟的动态内存
			SLDestroy(&ps);
			return false;
		    }
			//栈顶值
			val = SLTTop(&ps);
			//出栈
			SLPop(&ps);
			if (*s == ')' && val != '(' ||
				*s == ']' && val != '[' ||
				*s == '}' && val != '{')
			{
				SLDestroy(&ps);
				return false;
			}
		}
		s++;
	}
	bool ret = SLEmpty(&ps);
	SLDestroy(&ps);
	return ret;
}

My strength is limited and I may not explain clearly enough in some places. You can try to read the code by yourself, Wang Haihan!

Guess you like

Origin blog.csdn.net/weixin_71964780/article/details/132284190