Skip to content

Commit 67aa724

Browse files
committed
Min Stack/ Isomorphic Strings
1 parent 3bc534b commit 67aa724

File tree

2 files changed

+104
-0
lines changed

2 files changed

+104
-0
lines changed

155 Min Stack.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
'''
2+
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
3+
4+
push(x) -- Push element x onto stack.
5+
pop() -- Removes the element on top of the stack.
6+
top() -- Get the top element.
7+
getMin() -- Retrieve the minimum element in the stack.
8+
'''
9+
10+
class MinStack(object):
11+
def __init__(self):
12+
"""
13+
initialize your data structure here.
14+
"""
15+
self.stack = []
16+
self.minStack = []
17+
18+
def push(self, x):
19+
"""
20+
:type x: int
21+
:rtype: nothing
22+
"""
23+
self.stack.append(x)
24+
if not self.minStack:
25+
self.minStack.append(x)
26+
else:
27+
if self.minStack[-1] >= x:
28+
self.minStack.append(x)
29+
30+
def pop(self):
31+
"""
32+
:rtype: nothing
33+
"""
34+
if self.stack:
35+
if self.minStack[-1] == self.stack[-1]:
36+
self.minStack.pop()
37+
self.stack.pop()
38+
39+
def top(self):
40+
"""
41+
:rtype: int
42+
"""
43+
if self.stack:
44+
return self.stack[-1]
45+
46+
def getMin(self):
47+
"""
48+
:rtype: int
49+
"""
50+
if self.minStack:
51+
return self.minStack[-1]
52+
53+
54+
if __name__ == "__main__":
55+
minStack = MinStack()
56+
minStack.push(4)
57+
minStack.push(5)
58+
minStack.push(1)
59+
minStack.push(3)
60+
assert minStack.getMin() == 1
61+
minStack.pop()
62+
minStack.pop()
63+
assert minStack.top() == 5

205 Isomorphic Strings.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Given two strings s and t, determine if they are isomorphic.
3+
4+
Two strings are isomorphic if the characters in s can be replaced to get t.
5+
6+
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
7+
8+
For example,
9+
Given "egg", "add", return true.
10+
11+
Given "foo", "bar", return false.
12+
13+
Given "paper", "title", return true.
14+
15+
Note:
16+
You may assume both s and t have the same length.
17+
'''
18+
19+
class Solution(object):
20+
def isIsomorphic(self, s, t):
21+
"""
22+
:type s: str
23+
:type t: str
24+
:rtype: bool
25+
"""
26+
found = {}
27+
for c1, c2 in zip(s, t):
28+
if c1 in found:
29+
if not found[c1] == c2:
30+
return False
31+
else:
32+
if c2 in found.values():
33+
return False
34+
found[c1] = c2
35+
return True
36+
37+
38+
if __name__ == "__main__":
39+
assert Solution().isIsomorphic("egg", "add") == True
40+
assert Solution().isIsomorphic("foo", "bar") == False
41+
assert Solution().isIsomorphic("paper", "title") == True

0 commit comments

Comments
 (0)