-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathValid Parentheses.txt
49 lines (47 loc) · 1.12 KB
/
Valid Parentheses.txt
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
39
40
41
42
43
44
45
46
47
48
49
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.
------------------------------------------------------------------------
solution:
//用栈作辅助来模拟这个过程
//注意简化的部分,比如s.length()为0或者为奇数个时肯定不满足条件,还有当当前字符不在指定字符范围内时也可直接返回false
char symCharacter(char c)
{
switch(c)
{
case '(':
return ')';
case '[':
return ']';
case '{':
return '}';
default: //用返回'0'来标记当前字符无效
return '0';
}
}
bool isValid(string s)
{
stack<char> pstack;
if(s.length() == 0 || s.length() % 2 != 0)
return false;
for(int i = 0; i < s.length(); i++)
{
if(pstack.empty())
pstack.push(s[i]);
else
{
char c = pstack.top();
char t = symCharacter(c);
if(t== s[i])
pstack.pop();
else if(t == '0')
return false;
else
pstack.push(s[i]);
}
}
if(pstack.empty())
return true;
else
return false;
}