-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack
More file actions
50 lines (36 loc) · 1.34 KB
/
Stack
File metadata and controls
50 lines (36 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Reverse a string using stack:
def reverse_string(string):
return string[::-1]
Valid parentheses:
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
if not stack or stack.pop() != mapping[char]:
return False
else:
stack.append(char)
return not stack
Next greater element:
def nextLargerElement(self,arr,n):
stack = []
result = []
for i in range(n-1,-1,-1):
while (stack and arr[i] >= stack[-1]): stack.pop()
result.append(stack[-1] if stack else -1)
stack.append(arr[i])
return result[::-1]
Remove duplicates in letters:
def removeDuplicateLetters(self, s):
last_occ = {c: i for i, c in enumerate(s)}
stack = ["!"]
Visited = set()
for i, symbol in enumerate(s):
if symbol in Visited: continue
while (symbol < stack[-1] and last_occ[stack[-1]] > i):
Visited.remove(stack.pop())
stack.append(symbol)
Visited.add(symbol)
return "".join(stack)[1:]