20. Valid Parentheses
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
|
class
Solution {
public
:
bool
isValid(string s) {
if
(s.size() == 0 || s.size() % 2 == 1)
return
false
;
map<
char
,
char
> brackets;
brackets.insert(pair<
char
,
char
>(
'}'
,
'{'
));
brackets.insert(pair<
char
,
char
>(
']'
,
'['
));
brackets.insert(pair<
char
,
char
>(
')'
,
'('
));
stack<
char
> mystack;
for
(
int
i = 0 ;i < s.size();i++)
{
if
(s[i] ==
'{'
|| s[i] ==
'['
|| s[i] ==
'('
)
{
mystack.push(s[i]);
}
else
{
if
( mystack.size() < 1)
return
false
;
if
(brackets[s[i]] == mystack.top())
mystack.pop();
else
return
false
;
}
}
if
(mystack.size() == 0)
return
true
;
else
return
false
;
}
};
|
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1836722