I used the data structure "Stack" here,
which is convenient to solve this problem.
When the parenthesis is a left parenthesis,
I push it into the stack.
And when the parenthesis is a right parenthesis,
I'll judge whether it matches with the parenthesis on the top of the stack.
If it matches, stack.pop(),
but if it doesn't, these are not valid parentheses.
Loop this until there's no more parentheses.
The Runtime of the program is 3 ms.
The length of the code is 871 Bytes.
class Solution {
public:
bool isValid(string s) {
stack<char> st;
int i,len;
char ch;
len=s.length();
if (len==0) return true;
for (i=0; i<len; i++) {
ch=s[i];
if (ch==')') {
if (st.empty()) return false;
if (st.top()=='(')
st.pop();
else return false;
} else if (ch==']') {
if (st.empty()) return false;
if (st.top()=='[')
st.pop();
else return false;
} else if (ch=='}') {
if (st.empty()) return false;
if (st.top()=='{')
st.pop();
else return false;
} else st.push(ch);
}
if (st.empty()) return true;
else return false;
}
};