Postfix notation validation?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-02 03:03:35

问题


What would be a good way to evaluate a string(array, something) that contains a postfix expression(ex: 3 5 +) to check for validity?


回答1:


I'm assuming here that what you mean by valid is that executing the code will never underflow the stack and will leave a single value on the stack. If you have a more stringent notion of validity, you'll need a more sophisticated checker.

If you want to check for this kind of validity, it is not necessary to evaluate the string, and you can use a counter, not a stack. The counter tracks the number of values that would be on the stack if you evaluated. To simplify, let's suppose you have only literals, binary operators, and unary operators. This algorithm uses a special decrement operation: if when you decrement, the counter goes below zero, the string is invalid:

  1. Initialize the counter to 0.
  2. When you see a literal, increment the counter.
  3. When you see a binary operator, decrement the counter twice, then increment it.
  4. When you see a unary operator, decrement the counter, then increment it.
  5. At the end of the string, if the counter is 1, and if it never went below 0, the string is valid.



回答2:


Algorithm: maintain a stack and scan the postfix expression from left to right – If the element is a number, push it into the stack – If the element is a operator O, pop twice and get A and B respectively. Calculate BOA and push it back to the stack – When the expression is ended, the number in the stack is the final answer

//For validity If you are left with only one number in Stack its correct expression

//If you are left with more than one number in stack and no operator then its wrong

//If you have one or no number in stack and operators left then its wrong




回答3:


A postfix expression is valid if and only if:

1) The first two elements are operands(values), and

2) The last element is an operator, and

3) For every n values there are n-1 operator(s), and

4) In a list of n elements, starting at index i = 0 for i < n-1 (the second to last element), every group of elements consisting of k values( for k > 1 ) is followed by (k-1) operators. When k = 1, the number of operators that follows = k = 1.




回答4:


To check if a postfix expression is valid or not:(if input is in char array) 1.Number of operands must equal no. of operators + 1. To check this keep a check variable. check=0. Increment this for every operand and decrement for each operator.If finally its value is 1,then expression is valid.

2.The first 2 elements of the array need to be operands.No postfix expression can have operator as 1st or 2nd element. Check this by if control statement.



来源:https://stackoverflow.com/questions/789847/postfix-notation-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!