leetcode-20. Valid Parentheses 有效的括号 (C) 华为一面

leetcode 20. Valid Parentheses

华为base杭州通开一面题目

Given a string s 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.

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

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

思路

使用栈后进先出的性质。 我们需要知道的是,该题要求的几个条件:

  • brackets 类型和顺序要对应 比如{[]}是legal的但是{[]}]就是illegal的。
  • 一定要有左右bracket,右bracket做结尾。
  • 长度必须2的倍数

遍历一次string,把左括号都存进stack. 按照题中legal string的定义,那当我们遇到第一个右符号我们就需要判断栈中最后一个进的左括号,也就是栈最顶部的是否符合这个右括号。如果不符合,那就是false; 如果符合,把这个符合pop出来,或者把栈的长度减1,减去这个元素。

以此类推遍历整个string。

time complexity: O(n)

Space Complexity: O(n)

char pair(char a){
    if (a == '}') return '{';
    if (a == ']') return '[';
    if (a == ')') return '(';
    if (a == '>') return '<';
    return 0;

}

bool isValid(char * s){
    int n = strlen(s);
    //the length has to be multiple of 2
    if (n % 2 == 1) {
        return false;
    }
    int stack[n+1];
    int top = 0;
    for (int i = 0; i<n; i++){
        //iterate the string
        char ch = pair(s[i]);
        //recognize the right brackets
        if (ch){
            if (top == 0 || stack [top - 1] != ch){
                return false;
            }
            top--;
        }else 
            //Recognize the left brackets and put in the stack
            //push in the stack
        {
            stack[top++] = s[i];
        }
    }
    return top == 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值