valid parentheses

本文介绍了一种使用栈数据结构来验证括号是否正确配对的方法。通过遍历字符串中的每一种括号,判断其是否符合正确的开闭顺序,从而实现括号匹配的有效验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用栈来解决:

/*
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
 determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" 
and "([)]" are not.
*/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define STACK_TYPE char
typedef struct STACK_NODE {
	STACK_TYPE value;
	struct STACK_NODE *next;
} StackNode;
STACK_TYPE top(StackNode *stack_top);
int is_empty(StackNode *stack);
void push2(StackNode **stack_top,STACK_TYPE value);
void pop2(StackNode **stack_top);
int isValid(char* s) {
    StackNode *stack=NULL;
	char c;
	while(*s!='\0')
	{
		printf("%c\n",*s);
		switch(*s)
		{
			case '(':
			case '[':
			case '{': push2(&stack,*s);break;
			case ')': if(is_empty(stack) || top(stack)!='('){
						//	printf("top:%c\n",top(stack));
							return 0;
						}	
			          else pop2(&stack);break;
			case ']':  if(is_empty(stack) || top(stack)!='['){
						//	printf("top:%c\n",top(stack));
							return 0;
						}	
			          else pop2(&stack);break;
			case '}':  if(is_empty(stack) || top(stack)!='{'){
						//	printf("top:%c\n",top(stack));
							return 0;
						}	
			          else pop2(&stack);break;
			default:;
		}
		//printf("top:%c\n",top(stack));
		s++;
	}
	return is_empty(stack);
}
int main(int argc,char **argv)
{
	 char *s="([])[()";
	 printf("%d\n",isValid(s));
	return 0;
}
void push2(StackNode **stack_top,STACK_TYPE value)
{
	StackNode *new_node=(StackNode*)malloc(sizeof(StackNode));
	assert(new_node!=NULL);
	new_node->value=value;
	new_node->next=*stack_top;
	*stack_top=new_node;
}
void pop2(StackNode **stack_top)
{
	StackNode *first_node;
//	assert(!is_empty(*stack_top));
	first_node=*stack_top;
	*stack_top=first_node->next;
	free(first_node);
}
STACK_TYPE top(StackNode *stack_top)
{
	return (stack_top)->value;
}
int is_empty(StackNode *stack)
{
	return (stack)==NULL;
}

python:


# -*- coding: utf-8 -*-
'''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
 determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]"
and "([)]" are not.
'''
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        characters={')':'(',']':'[','}':'{'}
        stack=[]
        for c in s:
        	if c in characters.values():
        		stack.append(c)
        	elif c in characters.keys():
        		if stack==[] or characters[c]!=stack.pop():
        			return False
        	else:
        		return False
        return stack==[]
mystack=Solution()
s='[](){][}'
print mystack.isValid(s)









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值