当前位置: 代码迷 >> 综合 >> leetcode_23 Valid Parentheses
  详细解决方案

leetcode_23 Valid Parentheses

热度:97   发布时间:2024-01-29 17:28:42.0

题目:有效括号

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

如果字符是open则入栈,如果是close,则通过hashmap比较是否与栈顶括号成对,如果不成对,直接返回错误,如果成对,则栈顶元素出栈,继续下一个字符

class Solution {
public:unordered_map<char,char> map = {{ ')','('},{ ']','['},{ '}','{'}};bool isValid(string s) {if(s == "")    return true;stack<char> stk;for(int i = 0; i < s.length();i++){if(s[i] == '(' || s[i] == '[' || s[i] == '{'){stk.push(s[i]);}else if(s[i] == ')' || s[i] == ']' || s[i] == '}'){char tmp = map[s[i]];if(!stk.empty() && tmp == stk.top()){stk.pop();}elsereturn false;}elsereturn false;}if(stk.empty())    return true;return false; }
};

 

  相关解决方案