coding
unsky
deepdim
thought

Valid Parentheses

id20. Valid Parentheses Add to List QuestionEditorial Solution My Submissions
Total Accepted: 163285
Total Submissions: 507096
Difficulty: Easy
Contributors: Admin
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.

字符串匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.length();i++)
{if(s[i]=='('||s[i]=='['||s[i]=='{')
st.push(s[i]);
if(s[i]==')')
{if(st.empty())
return 0;
else{
if(st.top()=='(')
st.pop();
else return 0;
}
}
if(s[i]==']')
{if(st.empty())
return 0;
else{
if(st.top()=='[')
st.pop();
else return 0;
}}
if(s[i]=='}')
{
if(st.empty())
return 0;
else{if(st.top()=='{')
st.pop();
else return 0;
}}
}
if(st.empty())
return 1;
else return 0;
}
};

坚持原创技术分享,您的支持将鼓励我继续创作!