当前位置: 代码迷 >> 综合 >> 栈和队列:Validate Parenthesis
  详细解决方案

栈和队列:Validate Parenthesis

热度:28   发布时间:2024-01-20 03:06:04.0

Validate Parenthesis

前言:有一类问题有这样的特性:当前节点的解决依赖后驱节点。

对于某个当前节点,如果不能获知后驱节点,就无法得到有意义的解。

这类问题可以通过stack(或等同于stack的若干个临时变量)

解决:先将当前节点入栈,然后看其后继节点的值,直到其依赖的所有

节点都完备时,再从栈中弹出该节点求解。某些时候,甚至需要反复这个过程

:将当前节点的计算结果再次入栈,直到其依赖的后继节点完备。

看一个例子:

Validate Parenthesis

Given a string containing just the characters'(',')','{','}','[',']',

determine if the input string is a valid parentheses string.

For example "(([]))" is valid,but "(]" or "((" is not。

bool isLeftPartheses(char c)
{return c == '(' || c == '{' || c == '[';
}bool isMatchPartheses(char c, char s)
{switch(c){case ')':return s == '(';case ']':return s == '[';case '}':return s == '{';default:return false;}return false;
}bool isValidatePartheses(string str)
{stack<char> cst;for(int i = 0;i < str.size();i++){if(isLeftPartheses(str[i])){cst.push(str[i]);}else{if(cst.empty() || !isMatchPartheses(str[i],cst.top())){return false;}cst.pop();}   }//最后不是返回true,而是根据栈是否为空来判断是否合法return cst.empty();
}

 

  相关解决方案