Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
class Solution {
public:
bool isValid(string s) {
char tmpchar;
std::stack<char> st;
int counter = 0;
for (int i = 0; i < s.length(); i ++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
st.push(s[i]);
counter ++;
}
if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
if (counter < 1) {
return false;
}
tmpchar = st.top();
st.pop();
if ((s[i] == ')' && tmpchar != '(')
|| (s[i] == ']' && tmpchar != '[')
|| (s[i] == '}' && tmpchar != '{'))
{
return false;
}
counter --;
}
}
return counter == 0;
}
};
