def calculate(self, s):
     """
     :type s: str
     :rtype: int
     """
     stack=[]
     sign='+'
     val=0
     result=0
     for i in range(len(s)):
         if s[i].isdigit():
             val=val*10+(ord(s[i])-ord('0'))
         if (not s[i].isdigit() and s[i]!=' ') or i==len(s)-1:
             if sign=='+':
                 stack.append(val)
             if sign=='-':
                 stack.append(-1*val)
             if sign=='*':
                 stack.append(stack.pop()*val)
             if sign=='/':
                 ele=stack.pop()
                 if ele<0:
                     ele=-1*ele
                     ele=ele/val
                     ele=-1*ele
                 else:
                     ele=ele/val
                 stack.append(ele)
             sign=s[i]
             val=0
         # print(stack,sign,val)
     while len(stack)>0:
         result=result+stack.pop()
     return result
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack = list(s)
        print (stack)
        temp_stack = []

        while stack:
            ele = stack.pop()
            if ele.isnumeric():
                while stack and stack[-1].isnumeric():
                    ele += stack.pop()
                res = int(ele[::-1])
                y = ""
                while temp_stack:
                    ele2 = temp_stack.pop()
                    if ele2 != ']':
                        if ele2 != '[':
                            y += ele2
                    else:
                        break
              
                z = ""
                for _ in range(res): # z = y * res
                    z += y
                temp_stack.append(z)
                while temp_stack:
                    stack.append(temp_stack.pop())
            else:
                temp_stack.append(ele)

        temp_stack.reverse()
        return ("".join(temp_stack))
Exemple #3
0
 def isValid(self, s):
     """
     :type s: str
     :rtype: bool
     """
     if s==None or len(s)==0:
         return True
     stack=[]
     for i in range(len(s)):
         if s[i]=='[' or s[i]=='{' or s[i]=='(':
             if s[i]=='[':
                 stack.append(']')
             if s[i]=='{':
                 stack.append('}')
             if s[i]=='(':
                 stack.append(')')
         else:
             if len(stack)>0 and stack[-1]==s[i]:
                 stack.pop()
             else:
                 return False
     if len(stack)==0:
         return True
     return False
     
Exemple #4
0
 def removeKdigits(self, num, k):
     """
     :type num: str
     :type k: int
     :rtype: str
     """
     if k==0:
         return num
     if len(num)==1 and k==1:
         return '0'
     stack=[]
     stack.append(num[0])
     for i in range(1,len(num)):
         if num[i]>=stack[-1]:
             stack.append(num[i])
         else:
             while len(stack)!=0 and num[i]<stack[-1] and k>0:
                 stack.pop()
                 k=k-1
             stack.append(num[i])
     #checking for the k value .If it is not equal to 1 then we pop the elements till it becomes 1
     while k>0 and len(stack)>0:
         stack.pop()
         k=k-1
     #This condition is to check for trailing zeros
     if len(stack)==0 or ''.join(stack).lstrip('0')=='':
         return '0'
     else:
         return ''.join(stack).lstrip('0')
Exemple #5
0
 def exclusiveTime(self, n, logs):
     """
     :type n: int
     :type logs: List[str]
     :rtype: List[int]
     """
     prev=0
     curr=0
     stack=[]
     res=[0 for i in range(n)]
     for i in range(len(logs)):
         log=logs[i]
         val=log.split(':')
         functionid=int(val[0])
         curr=int(val[2])
         #when the function is start then we push it to the stack and we manage curr and prev.
         if val[1]=='start':
             if len(stack)>0:
                 res[stack[-1]]=res[stack[-1]]+curr-prev
                 prev=curr
             stack.append(functionid)
         #If the fucntion is end then we manage curr and prev and pop the element from the stack.
         else:
             res[functionid]=res[functionid]+curr-prev+1
             prev=curr+1
             stack.pop()
     return res
         
def symbolToOperator(symbol): 
    if symbol ==  '+': return plus()
    if symbol == '-': return minus()
    if symbol == '*': return multiply()
    if symbol == '/': return divide()

    def subtreePrefix(expr, index):
        parts = expr.split('')
        val = parts[index]
        opStack = []; # Start with the node at the index.
        valStack = []
        valCount = 0
        i = index + 1

        if (isOperator(val)):
            opStack.push(val)
        
        else:
            valStack.push(val)

        while (opStack.length and i < parts.length):
            val = parts[i]

            if (not isOperator(val) and valCount):
                valStack.push(compute(valStack.pop(), symbolToOperator(opStack.pop()), int(val)))

            elif (isOperator(val)):
                opStack.push(val)
                valCount = 0
            else:
                valStack.push(parseInt(val))
                valCount += 1

        i+=1

    if (Math.abs(index - i) % 2 == 0):
      i-=1

    return expr[index:i], index, i - 1 


    def evaluatePrefix(expr):
        parts = expr.split('')
        stack = []

    for j in range(len(expr) - 1,j >= 0):
       val = expr[j]

      // Push operated to stack.
      if (!isOperator(val)) {
        stack.push(parseInt(val));
      }
      else {
        // Operator found. Pop two elements from the stack.
         a = stack.pop();
         b = stack.pop();
        stack.push(compute(a, symbolToOperator(val), b));
      }
Exemple #7
0
 def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
     ans = [0] * len(temperatures)
     stack = []
     for i, t in enumerate(temperatures):
         while stack and t > temperatures[stack[-1]]:
             cur = stack.pop()
             ans[cur] = i - cur
         stack.append(i)
     return ans
Exemple #8
0
 def dailyTemperatures(self, T: List[int]) -> List[int]:
     stack = []
     ans = [0] * len(T)
     for i, v in enumerate(T):
         while stack and v > T[stack[-1]]:
             cur = stack.pop()
             ans[cur] = i - cur
         stack.append(i)
     return ans
Exemple #9
0
  def dailyTemperatures(self, T):
    ans = [0] * len(T)
    stack = []
    for i, t in enumerate(T):
      while stack and T[stack[-1]] < t:
        cur = stack.pop()
        ans[cur] = i - cur
      stack.append(i)

    return ans
Exemple #10
0
 def evalRPN(self, tokens: List[str]) -> int:
     stack=[]
     for i in tokens:
         if i!='+' and i!='-' and i!='*' and i!='/':
             stack.append(i)
         else:
             val0=int(stack.pop())
             val1=int(stack.pop())
             if i=='+':
                 stack.append(val0+val1)
             elif i=='-':
                 stack.append(val1-val0)
             elif i=='*':
                 stack.append(val0*val1)
             else:
                 stack.append(int(val1/val0))
         # print(stack,i)
     return stack[0]
     
     
Exemple #11
0
 def postorderTraversal(self, root):
     """
     :type root: TreeNode
     :rtype: List[int]
     """
     stack = []
     result = []
     cur = root
     if cur == None:
         return result
     
     
     while(cur != None):
         if cur.right:
             stack.append(cur.right)
         stack.append(cur)
         
         cur = cur.left
     #cur is the leftmost node
     
     while(len(stack)!=0):
         cur = stack.pop()
         #cur doesn't have right node
         #如果stack顶部的元素和cur一样,说明cur的右边节点还没有print完成,此时不可以pop cur,所以需要放回cur到stack顶部,把cur设置为右边subtree的parent node
         if cur.right is not None and (self.peek(stack) == cur.right):
             stack.pop()
             stack.append(cur) #Push it back
             cur = cur.right
             
             #find leftmost node of right subtree
             while cur:
                 if cur.right:
                     stack.append(cur.right)
                 stack.append(cur)
                 cur = cur.left
             
         else:
             result.append(cur.val)
             cur = None
     return result        
Exemple #12
0
 def verifyPreorder(self, preorder: List[int]) -> bool:
     lo = -inf
     stack = []
     
     for val in preorder:
         if val <= lo:
             return False
         
         while stack and stack[-1] < val:
             lo = stack.pop()
         
         stack.append(val)
     
     return True
Exemple #13
0
    def verifyPreorder(self, preorder: List[int]) -> bool:
        ## RC ##
        ## APPROACH : MONOTONOUS DECREASING STACK ##
        ## Similar to Leetcode: 94 Binary tree inorder traversal ##
        ## Similar to leetcode : 98 Validate Binary Search Tree #
        
        ## LOGIC ##
        ## 1. First we push all elements less than TOS (left childs)
        ## 2. If we encounter any big number than TOS, (indicates start of right childs), we pop all less elements and update lower value. In all such cases x should be more than its parent(lower) else we return False.
        ## 3. And append the big number to stack (right child) then (go for its left child & repeat process)
        
		## TIME COMPLEXITY : O(N) ##
		## SPACE COMPLEXITY : O(N) ##

        stack = []
        lower = -1 << 31
        for x in preorder:
            if x < lower:
                return False
            while stack and x > stack[-1]:
                lower = stack.pop()
            stack.append(x)
        return True
        
        # Then we realize that the preorder array can be reused as the stack thus achieve O(1) extra space, since the scanned items of preorder array is always more than or equal to the length of the stack.
        
        ## STACK TRACE ##
        ## [5,2,1,3,6] ##
        # [5, 2, 1, 3, 6]
        # [5, 2, 1, 3, 6]
        # [5, 2, 1, 3, 6]
        # [5, 3, 1, 3, 6]
        # [6, 3, 1, 3, 6]

		## TIME COMPLEXITY : O(N) ##
		## SPACE COMPLEXITY : O(1) ##

        lower = -1 << 31
        i = 0
        for x in preorder:
            if x < lower:
                return False
            while i > 0 and x > preorder[i - 1]:
                lower = preorder[i - 1]
                i -= 1
            preorder[i] = x
            i += 1
            # print(preorder)
        return True
Exemple #14
0
 def verifyPreorder(self, preorder: List[int]) -> bool:
     lower = -float('inf')
     stack = []
     
     for curr in preorder:
         if curr <= lower: # break BST rule
             return False
         if not stack or curr < stack[-1]:
             stack.append(curr)
             continue
         while stack and curr >= stack[-1]:
             lower = stack.pop()
         stack.append(curr)
         
     return True
 def nextGreaterElements(self, nums):
     """
     :type nums: List[int]
     :rtype: List[int]
     """
     stack=[]
     stack.append(0)
     n=len(nums)
     result=[-1 for i in range(len(nums))]
     #we do it for twice the lenth as it is a circular array
     for i in range(1,2*n):
         while len(stack)!=0 and nums[i%n]>nums[stack[-1]]:
             index=stack.pop()
             result[index]=nums[i%n]
         stack.append(i%n)
     return result
Exemple #16
0
 def dailyTemperatures(self, T):
     """
     :type T: List[int]
     :rtype: List[int]
     """
     stack=[]
     result=[0 for i in range(len(T))]
     stack.append(0)
     for i in range(1,len(T)):
         while len(stack)!=0 and T[i]>T[stack[-1]]:
             index=stack.pop()
             result[index]=i-index
         stack.append(i)
     return result
             
             
     
Exemple #17
0
        i += 1
    return True
  
  
------------------------------------------------------------------------------
Using stack for storing the current node as a check point for the next element.
Once the current is larger than the last element in the stack, we know we should take it as the right node.
The last element poping out from the stack will be also a checking point. We will use it to validate the BST property of the current element/node.

time complexity: O(n)
space complexity: O(n)

chk, stack = None, []
for n in preorder:
    while stack and n > stack[-1]:
        chk = stack.pop()
    if chk != None and n < chk:
        return False
    stack.append(n)
return True
Example 1: [5, 2, 6, 1, 3]
n = 5, stack = [5]
no checking point

Tree: 5
n = 2, 2 < 5, stack = [5, 2]
no checking point

Tree:   5
       /
	  2
Exemple #18
0
The algorithm has two steps:

Find the midpoint of the linked list
Push the second half values into the stack
Pop values out from the stack, and compare them to the first half of the linked list
The advantages of this algorithm are we don't need to restore the linked list and the space complexity is acceptable (O(N/2))

def isPalindrome(self, head):

    if not head or not head.next:
        return True

    # 1. Get the midpoint (slow)
    slow = fast = cur = head
    while fast and fast.next:
        fast, slow = fast.next.next, slow.next
    
    # 2. Push the second half into the stack
    stack = [slow.val]
    while slow.next:
        slow = slow.next
        stack.append(slow.val)

    # 3. Comparison
    while stack:
        if stack.pop() != cur.val:
            return False
        cur = cur.next
    
    return True
Exemple #19
0
stack = [] 

# append() function to push 
# element in the stack 
stack.append('a') 
stack.append('b') 
stack.append('c') 

print('Initial stack') 
print(stack) 

# pop() fucntion to pop 
# element from stack in 
# LIFO order 
print('\nElements poped from stack:') 
print(stack.pop()) 
print(stack.pop()) 
print(stack.pop()) 

print('\nStack after elements are poped:') 
print(stack) 

# uncommenting print(stack.pop()) 
# will cause an IndexError 
# as the stack is now empty 




#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  QUEUE  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
A Queue is a linear structure which follows a particular order in which the operations are performed. 
Exemple #20
0
            value - a copy of the value at the top of stack (?)
        -------------------------------------------------------
        """
        assert (len(self._values) > 0), 'Cannot peek at an empty stack'

        # Your code here

        return

    def pop(self):
        """
        -------------------------------------------------------
        Pops and returns the top of stack. The value is removed
        from the stack. Attempting to pop from an empty stack
        throws an exception.
        Use: value = stack.pop()
        -------------------------------------------------------
        Returns:
            value - the value at the top of stack (?)
        -------------------------------------------------------
        """
        assert (len(self._values) > 0), 'Cannot pop from an empty stack'

        # Your code here

        return

    def push(self, value):
        """
        -------------------------------------------------------
        Pushes a copy of value onto the top of the stack.