๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][BOJ] 1439๋ฒˆ ๋’ค์ง‘๊ธฐ

๋ฐ˜์‘ํ˜•

[BOJ] 1439๋ฒˆ ๋’ค์ง‘๊ธฐ

https://www.acmicpc.net/problem/1439

๋ฌธ์ œ์ ‘๊ทผ

0์ด ๊ฐ™์ด ์žˆ๋Š” ๊ทธ๋ฃน๊ณผ 1์ด ๊ฐ™์ด ์žˆ๋Š” ๊ทธ๋ฃน์ด ๋ช‡ ๊ทธ๋ฃน์ธ์ง€ ์„ธ๋ฉด ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ ์ฒ˜์Œ์—๋Š” 0์—์„œ 1๋กœ ๋ฐ”๋€Œ๋Š” ๋ถ€๋ถ„์—์„œ cnt์— +1์„ ํ•ด์ค€๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋ชจ๋“  ๊ทธ๋ฃน์„ ๋‹ค ์„ธ๊ธฐ ๋•Œ๋ฌธ์— ์˜ค๋‹ต์ด ๋˜์—ˆ๋‹ค. ๊ทธ๋ž˜์„œ zeroGroup๊ณผ oneGroup์„ ์ด์šฉํ•ด์„œ ๊ฐ์ž ๋”ฐ๋กœ๋”ฐ๋กœ ํ•˜๋‚˜์”ฉ ์„ธ์„œ ๋” ์ž‘์€ ๊ฐ’์„ ์ถœ๋ ฅํ•ด ์ฃผ์—ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„์— ์žˆ๋Š” ๊ทธ๋ฃน์€ ์ฒ˜์Œ ๋กœ์ง์œผ๋กœ๋Š” ์นด์šดํŠธ๊ฐ€ ์•ˆ๋˜์„œ for๋ฌธ ๋งˆ์ง€๋ง‰์ผ ๋•Œ ํ˜„์žฌ cur๊ฐ’์˜ group์— +1์„ ํ•ด์ฃผ์—ˆ๋‹ค.

Code

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        char prev = input.charAt(0);
        int zeroGruop = 0, oneGroup = 0; // ๊ฐ๊ฐ ๊ทธ๋ฃน์„ ๋‚˜๋ˆ„์–ด ์นด์šดํŒ…
        for(int i=1; i<input.length(); i++){
            char cur = input.charAt(i);
            if(prev != cur){
                // ํ˜„์žฌ ๊ฐ’๊ณผ ์ด์ „ ๊ฐ’์ด ๋‹ค๋ฅด๋ฉด ์ด์ „ ๊ฐ’์˜ ๊ทธ๋ฃน์˜ +1
                if(prev == '0')
                    zeroGruop++;
                else
                    oneGroup++;
            }
            if(i==input.length()-1){
                // ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค์— ์†ํ•œ ๊ทธ๋ฃน๋„ +1์„ ํ•ด์ฃผ๊ธฐ ์œ„ํ•ด์„œ ์ถ”๊ฐ€
                if(cur == '0')
                    zeroGruop++;
                else
                    oneGroup++;
            }
            prev = cur;
        }
        // ๋‘ ๊ทธ๋ฃน ์ค‘ ์ตœ์†Œ๊ฐ’์„ ๊ฐ€์ง„ ๊ทธ๋ฃน ์ถœ๋ ฅ
        System.out.println(Math.min(zeroGruop, oneGroup));
    }
}

์–ด๋ ค์› ๋˜ ์ / ๋ฐฐ์šด ์ 

์ด์ œ ์ž๋ฐ” ๋ฌธ๋ฒ•์— ์ต์ˆ™ํ•ด์ ธ์„œ ์–ด๋–ค ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์จ์•ผํ•  ์ง€ ๋Š๋‚Œ์ด ์˜ค๊ณ  String์— ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๋„ ์ ์‘์ด ๋œ ๊ฒƒ ๊ฐ™๋‹ค.
BOJ๋Š” ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค๋‚˜ LeetCode ์ฒ˜๋Ÿผ ์ข‹์•„์š”๋ฅผ ๋งŽ์ด ๋ฐ›์€ ์ฝ”๋“œ๋ฅผ ๋”ฐ๋กœ ๋ณผ ์ˆ˜ ์—†๋Š” ๊ฒƒ ๊ฐ™์•„์„œ ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์ด ์–ด๋–ป๊ฒŒ ํ’€์—ˆ์„์ง€ ๊ถ๊ธˆํ•˜๋‹ค.

๋ฐ˜์‘ํ˜•