算法题目: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.
大致意思:给定一个只包含’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’这六个字符的字符串,要求判断字符串是否满足要求,要求是:以正确的次序关闭,例如:”()” 、 “()[]{}” 和 “([])[{()}]”是正确的,而”(]” and “([)]”是错误的。
思路:典型的递归算法题,将字符串分成两个串s1、s2,初始化s1=”“,s2=s,判断字符串s1的末尾字符与s2的开头字符是否配对,若配对,则将s1的末尾字符删除,s2的开头字符串删除,若不配对,则将s2[0]移到s1的末尾,然后继续递归下去。
bool MyValidCore(string s1,string s2)
{
if(s1.size()==0&&s2.size()==0)return true;
else if(s1.size()>0&&s2.size()==0)return false;
if(s1.size()==0)
{
s1+=s2[0];
s2=s2.substr(1);
return MyValidCore(s1,s2);
}
int l1=s1.size();
if((s1[l1-1]=='('&&s2[0]==')')||(s1[l1-1]=='['&&s2[0]==']')||(s1[l1-1]=='{'&&s2[0]=='}'))
{
s1=s1.substr(0,l1-1);
s2=s2.substr(1);
}
else
{
s1+=s2[0];
s2=s2.substr(1);
}
return MyValidCore(s1,s2);
}
bool isValid(string s) {
if(s.size()==0||s.size()%2==1)return false;
return MyValidCore("",s);
}