题目描述
给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
示例1
输入
"["
返回值
false
示例2
输入
"[]"
返回值
true
题解
class Solution {
public:
/**
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
// write code here
if (s.empty()) {
return true;
}
string match;
match = match + s[0];
for (int i = 1; i < s.length(); i++) {
char ch = s[i];
if ((ch == '(') || ch == '[' || ch == '{') {
match = match + ch;
} else if ((ch == ')' && (match.back() == '('))
|| (ch == ']' && (match.back() == '['))
|| (ch == '}' && (match.back() == '{'))) {
match.erase(match.end() - 1);
} else {
return false;
}
}
if (!match.empty()) {
return false;
}
return true;
}
};
京公网安备 11010502036488号