Skip to content

Stack|Queue

Introduction

Each problem on the platform includes a direct solution, while others solely outline the approach within a function.


Solution

Source code in algorithms/stack/daily_temperatures.py
class Solution:
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype : List[int]
        """
        n = len(temperatures)
        answer = [0]*n
        stack = []

        for i in range(n):
            j =i+1
            while j < n and temperatures[i] > temperatures[stack[-1]]:
                prev_idx = stack.pop()
                answer[prev_idx] = i - prev_idx
            stack.append(i)
        return answer

dailyTemperatures(temperatures)

:type temperatures: List[int] :rtype : List[int]

Source code in algorithms/stack/daily_temperatures.py
def dailyTemperatures(self, temperatures):
    """
    :type temperatures: List[int]
    :rtype : List[int]
    """
    n = len(temperatures)
    answer = [0]*n
    stack = []

    for i in range(n):
        j =i+1
        while j < n and temperatures[i] > temperatures[stack[-1]]:
            prev_idx = stack.pop()
            answer[prev_idx] = i - prev_idx
        stack.append(i)
    return answer

Solution

Source code in algorithms/stack/roman_int.py
class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype : int
        """
        roman = {
            'I':1,
            'V':5,
            'X':10,
            'L':50,
            'C':100,
            'D':500,
            'M':1000
        }

        total = 0
        for i in range(len(s)-1):
            if roman[s[i]] < roman[s[i+1]]:
                total -= roman[s[i]]
            total += roman[s[i]]

        return total + roman[s[-1]]

romanToInt(s)

:type s: str :rtype : int

Source code in algorithms/stack/roman_int.py
def romanToInt(self, s):
    """
    :type s: str
    :rtype : int
    """
    roman = {
        'I':1,
        'V':5,
        'X':10,
        'L':50,
        'C':100,
        'D':500,
        'M':1000
    }

    total = 0
    for i in range(len(s)-1):
        if roman[s[i]] < roman[s[i+1]]:
            total -= roman[s[i]]
        total += roman[s[i]]

    return total + roman[s[-1]]