Problem: 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.
Analysis: A typical problem that uses stacks.
Note: For the function string::append(const char* pStr), it will append thewhole c-formatted-string associated by pStr to the string, but not the char pointed by the pointer pStr. For the second purpose, we need the function string::append(const char* pStr, int size).
Solution:
C++:
class Parentheses_Stack {
public:
void push(const char& paren) { stack.append(&paren, 1); }
char pop() {
char rChar('\0');
if(stack.empty())
return rChar;
rChar = stack[stack.size() - 1];
stack.erase(stack.end() - 1);
return rChar;
}
bool IsEmpty() { return stack.empty(); }
private:
string stack;
};
bool isValid(string s) {
Parentheses_Stack stack;
for(int i = 0; i < s.size(); ++i)
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
stack.push(s[i]);
else if((s[i] == ')' && stack.pop() != '(') ||
(s[i] == ']' && stack.pop() != '[') ||
(s[i] == '}' && stack.pop() != '{'))
return false;
if(!stack.IsEmpty())
return false;
return true;
}
Jave:
Python: