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();
else
return 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;
else
intStack.pop();
break;
case ']' :
if (intStack.empty() || '[' != intStack.top())
return false;
else
intStack.pop();
break;
case '}':
if (intStack.empty() || '{' != intStack.top())
return false;
else
intStack.pop();
break;
}
}
if (intStack.empty()) return true;
return false;
}
}; // runtime distribution 9.93%