LeetCode原题: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.
主要内容:判断给定string类字符串是否合法(三种类型的括号匹配)
解题思想:通过C++里面顺序容器中的stack栈结构实现。扫描string类字符串,判断每个字符,如果该字符属于左括号类型,则压入栈,如果不是则弹出栈顶,如果最后栈为空,则匹配成功,但是如果在该过程中弹出的栈顶与该非左括号类型字符不能完成括号匹配或者出现栈为空的情况,则匹配失败。
参考C++代码:
#include<stack>
class Solution {
public:
bool isLeft(char c) {
return (c == '(' || c == '{' || c == '[');
}
bool isMatch(char r, char l) {
if (l == '(') {
return (r == ')');
} else
if (l == '{') {
return (r == '}');
} else
if (l == '[') {
return (r == ']');
} else {
return false;
}
}
bool isValid(string s) {
stack<char> sc;
int z = s.size();
for (int i = 0; i < z; i++) {
if (isLeft(s[i])) {
sc.push(s[i]);
} else {
if(sc.empty() || !isMatch(s[i], sc.top())) {
return false;
}
sc.pop();
}
}
if(!sc.empty()) {
return false;
} else
return true;
}
};