题目
给定一个字符串,只包含’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和’]’这些字符,检查它是否是“有效”的。
括号必须以正确的顺序关闭,例如”()” 和”()[]{}”都是有效的,”(]” 和”([)]”是无效的。
分析:
本题考查的是栈结构,具有后进先出的特性。有效包含2个方面,第一个是如果是关闭的括号,前一位一定要刚好有一个开启的括号;第二个是最终结果,需要把所有开启的括号都抵消完。一个比较容易出错的地方是,遇到关闭括号时,要先判断栈是否已经空了。
- 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
代码
class Solution {
public:
bool isValid(string s) {
int s_length=(int)s.length();
std::stack<char> left_char_stack;
for(int i=0;i<s_length;i++) {
if( (s[i]=='(') || (s[i]=='[') || (s[i]=='{') ){
left_char_stack.push(s[i]);
}else{
if(left_char_stack.empty())
return false;
char tmp= left_char_stack.top();
if( (tmp=='('&&s[i]==')') || (tmp=='['&&s[i]==']') || (tmp=='{'&&s[i]=='}') ){
left_char_stack.pop();
}else{
return false;
}
}
}
if(left_char_stack.empty())
return true;
else
return false;
}
};