add postfix solns
This commit is contained in:
17
lintcode/271-prefix-notation-to-postfix-notation/README.md
Normal file
17
lintcode/271-prefix-notation-to-postfix-notation/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
Given a string array representing an expression, and return the Reverse Polish notation of this expression. (remove the parentheses)
|
||||
|
||||
Definition of _Reverse Polish Notation_:
|
||||
|
||||
* [https://en.wikipedia.org/wiki/Reverse\_Polish\_notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation)
|
||||
|
||||
Example
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: ["3", "-", "4", "+", "5"] Output: ["3", "4", "-", "5", "+"] Explanation: 3 - 4 + 5 = -1 + 5 = 4 3 4 - 5 + = -1 5 + = 4
|
||||
|
||||
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: ["(", "5", "-", "6", ")", "*", "7"] Output: ["5","6","-","7","*"] Explanation: (5 - 6) * 7 = -1 * 7 = -7 5 6 - 7 * = -1 7 * = -7
|
||||
@@ -0,0 +1,49 @@
|
||||
from typing import (
|
||||
List,
|
||||
)
|
||||
|
||||
from collections import deque
|
||||
|
||||
class Solution:
|
||||
"""
|
||||
@param expression: A string array
|
||||
@return: The Reverse Polish notation of this expression
|
||||
"""
|
||||
def convert_to_r_p_n(self, expression: List[str]) -> List[str]:
|
||||
op_priority = {
|
||||
'/': 1 << 4,
|
||||
'*': 1 << 4,
|
||||
'+': 1 << 2,
|
||||
'-': 1 << 2,
|
||||
'(': 1 << 0
|
||||
}
|
||||
|
||||
op_stack = deque()
|
||||
result = []
|
||||
|
||||
for token in expression:
|
||||
if token.isdigit():
|
||||
result.append(token)
|
||||
|
||||
elif token == '(':
|
||||
op_stack.append(token)
|
||||
|
||||
elif token == ')':
|
||||
while len(op_stack) > 0 and op_stack[-1] != '(':
|
||||
result.append(op_stack.pop())
|
||||
|
||||
op_stack.pop()
|
||||
|
||||
else:
|
||||
# For any other operator, keep popping and appending to results as long as there
|
||||
# are higher priority operators in the stack
|
||||
while len(op_stack) > 0 and op_priority[op_stack[-1]] >= op_priority[token]:
|
||||
result.append(op_stack.pop())
|
||||
|
||||
op_stack.append(token)
|
||||
|
||||
# Pop and append the remaining operators in the stack
|
||||
while len(op_stack) > 0:
|
||||
result.append(op_stack.pop())
|
||||
|
||||
return result
|
||||
Reference in New Issue
Block a user