【简单】20-有效的括号 Valid Parentheses

题目

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.

Example 1:

Input: "()"
Output: true

Example 2:

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

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

来源:力扣(Leetcode)
链接:https://leetcode.com/problems/valid-parentheses/

解法

方法一:栈

解题思路

括号分为左括号和右括号,有效的括号一定以左括号开始右括号结尾,且右括号与其前方第一个没有被对应的左括号对应,用一个栈存储所有的左括号,按字符串顺序遍历,当遇到左括号时就将其放入栈中等待遇到右括号与其对应,遇到右括号时就检查前方也就是当前的栈顶符号是否是与其对应的左括号,如果是就是将这个左括号弹出栈,表示其已经找到了对应的右括号,如果不是或者栈是空的,那就是无效的,到最后如果栈中没有元素了,就证明所有左括号都找到了与其对应的右括号,也就是有效的。

代码

class Solution {
public:
    bool isValid(string s) {
        map<char,char> par;
        par[')'] = '(';
        par['}'] = '{';
        par[']'] = '[';
        stack<char> temp;
        for(int i = 0; i < s.size(); ++i){
            if(s[i] == '(' || s[i] == '[' || s[i] == '{') temp.push(s[i]);
            else if(temp.empty() || temp.top() != par[s[i]]) return false;
            else temp.pop();
        }
        if(temp.empty()) return true;
        else return false;
    }
};
posted @ 2020-04-23 23:09  陌良  阅读(116)  评论(0)    收藏  举报