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.
有效字符串问题
递归算法:
这里只要把字符串的内容遍历一遍。用一个栈Stack来保存左边括号,遇到右边括号就和栈顶元素去匹配,匹配成功继续往后走,匹配失败迭代结束。
当整个字符串都遍历完成之后,要检查stack是否为空,如果不为空证明左侧括号数量多了,返回FALSE。
class Solution {
public:
bool isValid(string s) {
int len = s.length();
if (0 == len) return true;
stack<char> v;
for (int i = 0; i < len; i++){
if (isLeft(s[i])) v.push(s[i]);
else{
if (v.empty()) return false;
else{
if (isCouple(v.top(), s[i])){
v.pop();
}
else{
return false;
}
}
}
}
if(v.empty())
return true;
else
return false;
}
bool isCouple(char a,char b){<span style="white-space:pre"> </span>//检查是否匹配
switch (a){
case '(':
if (b == ')') return true;
else return false;
break;
case '[':
if (b == ']') return true;
else return false;
break;
case '{':
if (b == '}') return true;
else return false;
break;
}
}
bool isLeft(char a){ <span style="white-space:pre"> </span>//确定括号方向
if (a == '(' || a == '{' || a == '['){
return true;
}
else{
return false;
}
}
};
递归算法:
class Solution {
public:
bool isValid(string s) {
int len = s.length();
if (0 == len) return true;
if(len%2) return false;
for (int i = 0; i < len; i++){
if(isCouple(s[i-1], s[i])
{
string ss = s.substr(0, i-1) + s.substr(i+1);
return isValid(ss);
}
}
return false;
}
bool isCouple(char a,char b){
switch (a){
case '(':
if (b == ')') return true;
else return false;
break;
case '[':
if (b == ']') return true;
else return false;
break;
case '{':
if (b == '}') return true;
else return false;
break;
}
}
};