问题
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:
- Initialize the counter to 0.
- When you see a literal, increment the counter.
- When you see a binary operator, decrement the counter twice, then increment it.
- When you see a unary operator, decrement the counter, then increment it.
- 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