99클럽 코테 스터디 21일차 TIL [LeetCode] Minimum Suffix Flips (Java)

민경·2024년 6월 18일

문제

[LeetCode]
Minimum Suffix Flips

풀이

0으로 이루어진 이진 문자열을 주어진 이진 문자열 target과 같은 문자열로 만들기 위한 최소 뒤집기 횟수를 찾는 문제

  • 문자열을 처음부터 끝까지 순회한다.
  • 현재 문자가 current와 다르면 flips를 증가시키고, current를 현재 문자로 업데이트한다.
  • 반복문이 종료되면, flips를 반환한다.

정답 코드

class Solution {
    public int minFlips(String target) {
        int flips = 0;
        char current = '0';

        for (int i = 0; i < target.length(); i++) {
            if (target.charAt(i) != current) {
                flips++;
                current = target.charAt(i);
            }
        }

        return flips;
    }
}
profile
강해져야지

0개의 댓글