标签:字符串
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
本文出自 “做最好的自己” 博客,请务必保留此出处http://qiaopeng688.blog.51cto.com/3572484/1836722
leetCode 20. Valid Parentheses 字符串
标签:字符串
原文地址:http://qiaopeng688.blog.51cto.com/3572484/1836722