본문 바로가기
Leetcode

[LeetCode] Max Consecutive Ones 파이썬 (문자열 압축)

by YGSEO 2021. 4. 29.
728x90
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        local_max = 0
        tmp = 0
        for i in nums:
            if i == 1:
                tmp += 1
            else:
                # print(local_max, tmp)
                local_max = max(local_max, tmp)
                tmp = 0
        else:
            local_max = max(local_max, tmp)
        return local_max

주의점:

loop가 정상적으로 순회한 후에도 max값이 update가 안되어있을 수 있기 때문에

for-else문을 통해 update 시켜줘야 한다.

 

카카오 문자열 압축 문제에서도 나온 유의사항.

 

다른 풀이는

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result, local_max = 0, 0
        for n in nums:
            local_max = (local_max + 1 if n else 0)
            result = max(result, local_max)
        return result

삼항 연산자를 사용해서 깔끔하게 표현하는 방법

 

출처: github.com/jiapengwen/LeetCode/blob/master/Python/max-consecutive-ones.py

 

 

문자열 압축: ygseo.tistory.com/128
728x90

댓글