20. Valid Parentheses [LeetCode]

20Valid Parentheses

对比LeetCode125:Valid Palindrome

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

平衡符号判定问题,经典的栈应用问题(关于栈的应用还有几个经典场景:Postfix Expressions和Infix to Postfix Conversion ).

/**************************************************************************
 * 
 * 20. [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)
 * 
 * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
 * An input string is valid if:
 * Open brackets must be closed by the same type of brackets.
 * Open brackets must be closed in the correct order.
 * 
 * Example 1:
 * Input: s = "()"
 * Output: true
 * 
 * Example 2:
 * Input: s = "()[]{}"
 * Output: true
 * 
 * Example 3:
 * Input: s = "(]"
 * Output: false
 * 
 * Similar Questions: 125. [Valid Palindrome]
 **************************************************************************/


int findPair(int s) {
    switch (s) {
        case ')': return '(';
        case ']': return '[';
        case '}': return '{';
        default : return -1;
    }
}

// 用数组模拟栈  index = -1 表示栈空  index指向栈顶元素
bool isValid(char * s){
    int len = strlen(s);
    if (len < 2) return false;
    
    int index = -1;
    char *ret = (char *)calloc(len, sizeof(char));
    
    for (int i = 0; i < len; i++) {
        if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
            index++;
            ret[index] = s[i];
        } else {
            if (index == -1) return false;
            if (ret[index] != findPair(s[i])) return false;
            index--;
        }
    }
    free(ret);
    return index == -1;
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luuyiran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值