每天算法之十九:Valid Parentheses
每日算法之十九:Valid Parentheses
这个就是查看括号是否是匹配的。使用STL中的stack是容易实现的。代码如下:
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
,
determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are
all valid but "(]"
and "([)]"
are
not.
class Solution { public: bool iscombine(char s,char p)//比较两个字符是否匹配。只有三种情况是匹配的 { if(s == '('&&p == ')') return true; if(s == '['&&p == ']') return true; if(s == '{'&&p == '}') return true; else return false; } bool isValid(string s) { if(s.size() == 0) return false; if(s.size()%2!=0) return false;//如果字符串长度是奇数,显然是不可能匹配的。 stack<char> valid_stack;//pop()成员函数删除栈顶元素,不返回。top()成员函数返回栈顶元素,不删除. for(int i = 0;i<s.size();i++) { if(valid_stack.empty())//如果栈为空,直接添加字符进去。如果没有这样。会越界,报错。 { valid_stack.push(s[i]); continue; } if(iscombine(valid_stack.top(),s[i])) valid_stack.pop(); else valid_stack.push(s[i]); } if(valid_stack.empty())//最后为空,即所有的括号都已经匹配了。 return true; else return false; } };