letecode [20] - Valid Parentheses
Given a string 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.
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
题目大意:
给定“括号”字符串,判断该字符串是否合法。
合法要求:1.左括号必须用相同类型的右括号闭合 2.左括号必须以正确的顺序闭合
理 解:
设计一个括号栈,当字符为左括号时读入栈,当字符为右括号时判断栈顶元素是否为对应的左括号,满足要求1,
栈顶元素为对应左括号,则弹出,满足要求2.
不满足要求的条件,返回false.
代 码 C++:
class Solution { public: bool isValid(string s) { if(s=="") return true; int i=0; stack<char> sta; while(s[i]!='\0'){ if(s[i]=='('||s[i]=='{'||s[i]=='['){ sta.push(s[i]); } else if(s[i]==')'){ if(sta.empty()==true) return false; if(sta.top()=='('){ sta.pop(); }else{ return false; } } else if(s[i]=='}'){ if(sta.empty()==true) return false; if(sta.top()=='{'){ sta.pop(); }else{ return false; } } else if(s[i]==']'){ if(sta.empty()==true) return false; if(sta.top()=='['){ sta.pop(); }else{ return false; } } else{ return false; } ++i; } if(sta.empty()==true) return true; else return false; } };