๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] ์• ๋„ˆ๊ทธ๋žจ ๋งŒ๋“ค๊ธฐ BOJ #1919

by seolhee2750 2021. 7. 30.
๋ฌธ์ œ ์„ค๋ช…

๋‘ ์˜์–ด ๋‹จ์–ด๊ฐ€ ์ฒ ์ž์˜ ์ˆœ์„œ๋ฅผ ๋’ค๋ฐ”๊พธ์–ด ๊ฐ™์•„์งˆ ์ˆ˜ ์žˆ์„ ๋•Œ, ๊ทธ๋Ÿฌํ•œ ๋‘ ๋‹จ์–ด๋ฅผ ์„œ๋กœ ์• ๋„ˆ๊ทธ๋žจ ๊ด€๊ณ„์— ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด occurs ๋ผ๋Š” ์˜์–ด ๋‹จ์–ด์™€ succor ๋Š” ์„œ๋กœ ์• ๋„ˆ๊ทธ๋žจ ๊ด€๊ณ„์— ์žˆ๋Š”๋ฐ, occurs์˜ ๊ฐ ๋ฌธ์ž๋“ค์˜ ์ˆœ์„œ๋ฅผ ์ž˜ ๋ฐ”๊พธ๋ฉด succor์ด ๋˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

ํ•œ ํŽธ, dared์™€ bread๋Š” ์„œ๋กœ ์• ๋„ˆ๊ทธ๋žจ ๊ด€๊ณ„์— ์žˆ์ง€ ์•Š๋‹ค. ํ•˜์ง€๋งŒ dared์—์„œ ๋งจ ์•ž์˜ d๋ฅผ ์ œ๊ฑฐํ•˜๊ณ , bread์—์„œ ์ œ์ผ ์•ž์˜ b๋ฅผ ์ œ๊ฑฐํ•˜๋ฉด, ared์™€ read๋ผ๋Š” ์„œ๋กœ ์• ๋„ˆ๊ทธ๋žจ ๊ด€๊ณ„์— ์žˆ๋Š” ๋‹จ์–ด๊ฐ€ ๋‚จ๊ฒŒ ๋œ๋‹ค.

๋‘ ๊ฐœ์˜ ์˜์–ด ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋‘ ๋‹จ์–ด๊ฐ€ ์„œ๋กœ ์• ๋„ˆ๊ทธ๋žจ ๊ด€๊ณ„์— ์žˆ๋„๋ก ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ ์ œ๊ฑฐํ•ด์•ผ ํ•˜๋Š” ์ตœ์†Œ ๊ฐœ์ˆ˜์˜ ๋ฌธ์ž ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋ฌธ์ž๋ฅผ ์ œ๊ฑฐํ•  ๋•Œ์—๋Š” ์•„๋ฌด ์œ„์น˜์— ์žˆ๋Š” ๋ฌธ์ž๋“ ์ง€ ์ œ๊ฑฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ œํ•œ ์กฐ๊ฑด

์ฒซ์งธ ์ค„๊ณผ ๋‘˜์งธ ์ค„์— ์˜์–ด ๋‹จ์–ด๊ฐ€ ์†Œ๋ฌธ์ž๋กœ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ๊ฐ์˜ ๊ธธ์ด๋Š” 1,000์ž๋ฅผ ๋„˜์ง€ ์•Š์œผ๋ฉฐ, ์ ์–ด๋„ ํ•œ ๊ธ€์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ

์ฒซ์งธ ์ค„์— ๋‹ต์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

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

์ž…๋ ฅ

aabbcc
xxyybb

์ถœ๋ ฅ

8

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import Foundation

let input1 = readLine()!
let input2 = readLine()!
var alphabet = Array("abcdefghijklmnopqrstuvwxyz")
var alpha1 = Array(repeating: 0, count: 26)
var alpha2 = Array(repeating: 0, count: 26)

var result = 0

for i in input1 { alpha1[alphabet.firstIndex(of: i)!] += 1 }
for i in input2 { alpha2[alphabet.firstIndex(of: i)!] += 1 }

for i in 0..<26 {
    if alpha1[i] > alpha2[i] { result += (alpha1[i] - alpha2[i]) }
    else { result += (alpha2[i] - alpha1[i]) }
}

print(result)
  • ์†Œ๋ฌธ์ž ์•ŒํŒŒ๋ฒณ์„ ๋‹ด์€ ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ , ์ž…๋ ฅ๋œ ๊ฐ ๋‹จ์–ด์˜ ์•ŒํŒŒ๋ฒณ ๊ฐœ์ˆ˜๋ฅผ ๋น„๊ตํ•˜๊ธฐ ์œ„ํ•ด
    ์•ŒํŒŒ๋ฒณ ๊ฐœ์ˆ˜๋งŒํผ์˜ ํฌ๊ธฐ๋ฅผ ๊ฐ€์ง„ ๋นˆ ๋ฐฐ์—ด ๋‘ ๊ฐœ alpha1, alpha2๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค.
  • ๋จผ์ € ์ž…๋ ฅ๋ฐ›์€ ๊ฐ ๋‹จ์–ด๋ฅผ ์ˆœ์„œ๋Œ€๋กœ ํ•œ ๊ธ€์ž์”ฉ ๊ฒ€์‚ฌํ•˜์—ฌ alphabet ๋ฐฐ์—ด์—์„œ ์œ„์น˜๋ฅผ ์ฐพ๊ณ ,
    ํ•ด๋‹นํ•˜๋Š” alpha1, alpha2 ๋ฐฐ์—ด์˜ ์œ„์น˜์— +1์„ ํ•ด์ฃผ์—ˆ๋‹ค.
  • alpha1๊ณผ alpha2 ๋ฐฐ์—ด์„ ๋น„๊ตํ•˜์—ฌ ๋ชจ๋“  ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜ ์ฐจ์ด๋ฅผ ๋ˆ„์ ํ•˜์—ฌ ๊ฒฐ๊ณผ๋กœ ์ถœ๋ ฅํ–ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์•ŒํŒŒ๋ฒณ ๋ฐฐ์—ด์„ ๋”ฐ๋กœ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  ๋น„๊ตํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค.
    ๋‹ค์Œ์—” ์•ŒํŒŒ๋ฒณ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ๋‹ค์‹œ ํ’€์–ด๋ด์•ผ๊ฒ ๋‹ค.

 


 

 

๋ฌธ์ œ

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

๋Œ“๊ธ€