Skip to content

Commit 37e0cd4

Browse files
committed
Evaluate Reverse Polish Notation/ Reverse Words in a String
1 parent c0fc001 commit 37e0cd4

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
3+
4+
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
5+
6+
Some examples:
7+
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
8+
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
9+
'''
10+
11+
class Solution(object):
12+
def evalRPN(self, tokens):
13+
"""
14+
:type tokens: List[str]
15+
:rtype: int
16+
"""
17+
stack = []
18+
for token in tokens:
19+
if token not in ("+", "-", "*", "/"):
20+
stack.append(int(token))
21+
else:
22+
second = stack.pop()
23+
first = stack.pop()
24+
if token == "+":
25+
stack.append(first + second)
26+
elif token == "-":
27+
stack.append(first - second)
28+
elif token == '*':
29+
stack.append(first * second)
30+
else:
31+
if first * second < 0:
32+
stack.append(-(abs(first) // abs(second)))
33+
else:
34+
stack.append(first // second)
35+
return stack.pop()
36+
37+
38+
if __name__ == "__main__":
39+
assert Solution().evalRPN(["2", "1", "+", "3", "*"]) == 9
40+
assert Solution().evalRPN(["4", "13", "5", "/", "+"]) == 6
41+
assert Solution().evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22

151 Reverse Words in a String.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'''
2+
Given an input string, reverse the string word by word.
3+
4+
For example,
5+
Given s = "the sky is blue",
6+
return "blue is sky the".
7+
8+
Update (2015-02-12):
9+
For C programmers: Try to solve it in-place in O(1) space.
10+
11+
Clarification:
12+
What constitutes a word?
13+
A sequence of non-space characters constitutes a word.
14+
Could the input string contain leading or trailing spaces?
15+
Yes. However, your reversed string should not contain leading or trailing spaces.
16+
How about multiple spaces between two words?
17+
Reduce them to a single space in the reversed string.
18+
'''
19+
20+
class Solution(object):
21+
def reverseWords(self, s):
22+
"""
23+
:type s: str
24+
:rtype: str
25+
"""
26+
return " ".join(s.split()[::-1])
27+
28+
29+
if __name__ == "__main__":
30+
assert Solution().reverseWords("the sky is blue ") == "blue is sky the"

0 commit comments

Comments
 (0)