给定一个字符串,里面只有(){}[]这六种字符,判断,是否它们能够匹配。
栈即可解决该问题。
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
|
class Solution {
public:
bool IsMatch(char left,char right) {
if(left == '{' && right == '}' ||
left == '[' && right == ']' ||
left == '(' && right == ')') {
return true;
}
else
return false;
}
bool isValid(string s) {
stack<int> sta;
for(int i = 0;i < s.length();i++) {
if(sta.size() == 0 || IsMatch(sta.top(),s[i]) == false) {
sta.push(s[i]);
}
else {
sta.pop();
}
}
if(sta.size() == 0) {
return true;
}
else
return false;
}
};
|