20. Valid Parentheses
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 isValid(string s) { if(s.size() == 0 || s.size() % 2 == 1) return false; map<char, char> brackets; brackets.insert(pair<char, char>('}', '{')); brackets.insert(pair<char, char>(']', '[')); brackets.insert(pair<char, char>(')', '(')); stack<char> mystack; for(int i = 0 ;i < s.size();i++) { if(s[i] == '{' || s[i] == '[' || s[i] == '(' ) { mystack.push(s[i]); } else { if( mystack.size() < 1) return false; if(brackets[s[i]] == mystack.top()) mystack.pop(); else return false; } } if(mystack.size() == 0) return true; else return false; } };
2016-08-11 00:30:15
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。