For MultiTek
Start to test at 2018 Feb 28 8:00
20. Valid Parentheses
20. Valid Parentheses
class Solution {
/*if c = '(' or '{' or '[', return true; otherwise, return false*/
bool isLeftOperator(char c) {
return ((c == '{') || (c == '[') || (c == '('));
}
bool isMatch(char c1, char c2) {
if (c1 == '}')
return (c2 == '{');
if (c1 == ']')
return (c2 == '[');
if (c1 == ')')
return (c2 =='(');
return false;
}
public:
// '(', ')', '{', '}', '[' and ']',
bool isValid(string s) {
/*use a stack to store the operators*/
stack<char> stack;
char now, c;
for (int i = 0; i < s.length(); i++) {
now = s.at(i);
if (isLeftOperator(now)) {
stack.push(now);
} else {
/*boundary condition*/
if (stack.empty())
return false;
char c = stack.top();
/*try to match*/
if (!isMatch(now, c)) {
return false;
}
stack.pop();
}
}
if (stack.empty()) {
return true;
} else {
return false;
}
}
};
2
留言
張貼留言