Leetcode 20 Valid Parentheses

Valid Parentheses
Total Accepted: 71209 Total Submissions: 265268 Difficulty: Easy

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.

这道题我的实现方法很简单,而这应该也是成对括号问题的通用处理方法。即建立一个堆栈,然后遍历字符串如果遇到左括号’(‘,’[‘,’{‘,就入栈,如果遇到右括号’)’,’]’,’}’就看当前栈顶的元素,如果是与之匹配的左括号,那就让这个左括号出栈,否则,匹配就是错误的返回false,当数组都遍历一遍后,我们查看如果栈是否为空,如果为空,说明所有括号都得到匹配,返回true,否则返回false。

下面是完整代码:

#include <iostream>
#include <stdio.h>
using namespace std;

bool isValid(char* s) 
{
    int size = strlen(s);
    char *stack = (char*)malloc(sizeof(char) * size);

    int top = -1;

    for(int i = 0; i < size; i++)
    {
        switch(s[i])
        {
        case '(': top++; stack[top] = '('; break;
        case '{': top++; stack[top] = '{'; break;
        case '[': top++; stack[top] = '['; break;
        case ')': 
            {
                if(top >=0 && stack[top] == '(')
                    top--;
                else
                    return false;
                break;
            }
        case '}':
            {
                if(top >=0 && stack[top] == '{')
                    top--;
                else
                    return false;
                break;
            }
        case ']':
            {
                if(top >=0 && stack[top] == '[')
                    top--;
                else
                    return false;
                break;
            }
        }
    }
    if(top == -1)
        return true;
    else 
        return false;
}

int main()
{
    char s[100];
    scanf("%s",s);
    cout<<isValid(s)<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值