Contents

A๋กœ B ๋งŒ๋“ค๊ธฐ (with.Java)

   May 24, 2024     1 min read

โ€œA๋กœ B ๋งŒ๋“ค๊ธฐ (with.Java)โ€ ๋ฌธ์ œ์— ๋Œ€ํ•˜์—ฌ ์•Œ์•„๋ณธ ๊ธ€์ž…๋‹ˆ๋‹ค.

์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉฐ, ํ’€์—ˆ๋˜ ๋ฌธ์ œ์— ๋Œ€ํ•œ ํšŒ๊ณ ์™€ ๋‹ค๋ฅธ ํ’€์ด ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด๋ฉฐ, ์•Œ์•„๊ฐ€๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค.

๋ฌธ์ œ์— ๋Œ€ํ•ด ๋จผ์ € ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

๋ฌธ์ œ

๋ฌธ์ž์—ด before์™€ after๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, before์˜ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์–ด after๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์œผ๋ฉด 1์„, ๋งŒ๋“ค ์ˆ˜ ์—†์œผ๋ฉด 0์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด๋ณด์„ธ์š”.

์ œํ•œ์‚ฌํ•ญ

  • 0 < before์˜ ๊ธธ์ด == after์˜ ๊ธธ์ด < 1,000
  • before์™€ after๋Š” ๋ชจ๋‘ ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

beforeafterresult
โ€œollehโ€โ€œhelloโ€1
โ€œallpeโ€โ€œappleโ€0

๋ฌธ์ œ์— ๋Œ€ํ•œ ๋‚˜์˜ ํ’€์ด

import java.util.Arrays;

class Solution {
    public int solution(String before, String after) {

        char[] beforeArray = before.toCharArray();
        char[] afterArray = after.toCharArray();
        Arrays.sort(beforeArray);
        Arrays.sort(afterArray);

        return Arrays.equals(beforeArray, afterArray) ? 1 : 0;
    }
}

ํ’€์ด ๋ฆฌ๋ทฐ

๋จผ์ €, ์ž…๋ ฅ๋œ ๋‘ ๋ฌธ์ž์—ด before์™€ after๋ฅผ ๊ฐ๊ฐ ๋ฌธ์ž ๋ฐฐ์—ด(char[])๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

Arrays.sort() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋‘ ๋ฌธ์ž ๋ฐฐ์—ด์„ ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋‘ ๋ฌธ์ž์—ด์˜ ๊ฐ ๋ฌธ์ž๊ฐ€ ์ •๋ ฌ๋œ ์ƒํƒœ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

Arrays.equals() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ •๋ ฌ๋œ ๋‘ ๋ฌธ์ž ๋ฐฐ์—ด์ด ์„œ๋กœ ๊ฐ™์€์ง€๋ฅผ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.

์ด ํ•จ์ˆ˜๋Š” ๋‘ ๋ฐฐ์—ด์ด ๊ฐ™์€์ง€๋ฅผ ๋น„๊ตํ•˜์—ฌ true ๋˜๋Š” false๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

๋งŒ์•ฝ ์ •๋ ฌ๋œ ๋‘ ๋ฌธ์ž ๋ฐฐ์—ด์ด ๊ฐ™๋‹ค๋ฉด, ์ฆ‰, ๋‘ ๋ฌธ์ž์—ด์ด ๊ฐ™์€ ๋ฌธ์ž๋“ค์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๋ฉด, 1์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด 0์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์ž…๋ ฅ๋œ ๋ฌธ์ž์—ด์ด ๋™์ผํ•œ ๋ฌธ์ž๋“ค๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋Š”์ง€๋ฅผ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ๋ฌธ์ž์—ด์„ ์ •๋ ฌํ•˜์—ฌ ๋น„๊ตํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.