本文主要是介绍leetcode 20 parenthesis match,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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) {typedef string::size_type sz;sz size = s.size();map<char, char> mp = { {')', '('}, {']', '['}, {'}', '{'}}; // make_pair(')', '(');typedef map<char, char>::const_iterator miter;vector<char> v;v.reserve(size);typedef vector<char>::const_iterator viter;for (sz i = 0; i != size; ++i) {char tmp = s[i];miter mit = mp.find(tmp);if (mit == mp.end())v.push_back(tmp);else {if (mit->second == *(v.rbegin()))v.pop_back();elsereturn false;}}if (v.empty()) return true;return false;}
}; // runtime distribution 9.93%
参考后
class Solution {
public:bool isValid(string s) {typedef string::size_type sz;sz size = s.size();stack<char> intStack;typedef vector<char>::const_iterator viter;for (sz i = 0; i != size; ++i) {char tmp = s[i];switch (s[i]){case '(' :case '[' :case '{' : intStack.push(s[i]);break;case ')' :if (intStack.empty() || '(' != intStack.top())return false;elseintStack.pop(); break;case ']' :if (intStack.empty() || '[' != intStack.top())return false;elseintStack.pop();break;case '}':if (intStack.empty() || '{' != intStack.top())return false;elseintStack.pop();break;}}if (intStack.empty()) return true;return false;}
}; // runtime distribution 9.93%
这篇关于leetcode 20 parenthesis match的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!