상세 컨텐츠

본문 제목

[LeetCode][Python]1758. Minimum Changes To Make Alternating Binary String

공부

by 근성 2023. 12. 26. 12:38

본문

[구현]

주어진 문자열은 '0'과 '1'로만 구성되었다.

한 번의 작업에서 '0'을 '1'로 변경하거나 그 반대의 경우도 변경할 수 있다.

인접한 두 문자가 동일하지 않으면 이 문자열은 교대라고 한다.

예를 들어, 문자열 "010"은 교대하는 반면, 문자열 "0100"은 교대하지 않는다.

교대하는 데 필요한 최소 작업 수를 구하는것이 문제이다.

 

Example 1:

Input: s = "0100"
Output: 1
Explanation: If you change the last character to '1', s will be "0101", which is alternating.

 

Example 2:

Input: s = "10"
Output: 0
Explanation: s is already alternating.

 

Example 3:

Input: s = "1111"
Output: 2
Explanation: You need two operations to reach "0101" or "1010".

 

 

문자열의 index를 통해 반복문을 수행하는데,

해당 index가 짝수일때 1, 홀수일 때 0을 counting해서

카운팅한값과 주어진 문자열의 길이에서 카운팅한 값을 뺀값이 최소가 된다.

 

class Solution:
    def minOperations(self, s: str) -> int:
        answer = 0
        
        for i in range(len(s)):
            if i % 2 == 0:
                if s[i] == "1":
                    answer += 1
            else:
                if s[i] == "0":
                    answer += 1
        
        return min(answer, len(s) - answer)

관련글 더보기

댓글 영역