Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 10809๋ฒˆ - ์•ŒํŒŒ๋ฒณ ์ฐพ๊ธฐ

๊ฐ์ž ๐Ÿฅ” 2022. 2. 15. 12:42
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ๋งํฌ

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

 

10809๋ฒˆ: ์•ŒํŒŒ๋ฒณ ์ฐพ๊ธฐ

๊ฐ๊ฐ์˜ ์•ŒํŒŒ๋ฒณ์— ๋Œ€ํ•ด์„œ, a๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜, b๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜, ... z๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜๋ฅผ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•œ๋‹ค. ๋งŒ์•ฝ, ์–ด๋–ค ์•ŒํŒŒ๋ฒณ์ด ๋‹จ์–ด์— ํฌํ•จ๋˜์–ด ์žˆ์ง€ ์•Š๋‹ค๋ฉด -1์„ ์ถœ

www.acmicpc.net

 

๋‚ด๊ฐ€ ํ‘ผ ํ’€์ด

  • ์ž…๋ ฅ๋ฐ›์„ ๋ฌธ์ž๋ฐฐ์—ด line / ๊ฒ€์‚ฌ๊ฐ€ ์™„๋ฃŒ๋œ ๊ธ€์ž๋ฅผ ๋„ฃ์–ด์ฃผ๋Š” char ๋ฐฐ์—ด left / ์ •๋‹ต๋ฐฐ์—ด answer
  • ์ •๋‹ต ๋ฐฐ์—ด์—๋Š”, ๋“ฑ์žฅํ•˜์ง€ ์•Š์€ ๋ฌธ์ž๋Š” -1 ์ด ๋“ค์–ด๊ฐ€์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ์šฐ์„  -1์„ 26๊ฐœ ์ฑ„์› ๋‹ค. (a...z๋Š” 26๊ฐœ)
  • ๋‚˜๋Š” line์—์„œ ํ•œ๊ธ€์ž์”ฉ for in ๊ตฌ๋ฌธ์œผ๋กœ ๋”ฐ์™€์„œ, ํ•ด๋‹น char์˜ asciiValue๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ช‡๋ฒˆ์งธ ์•ŒํŒŒ๋ฒณ์ธ์ง€ answer๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค ๊ฐ’์„ ๊ตฌํ–ˆ๋‹ค. 
  • ๊ทธ๋ฆฌ๊ณ  ๊ฒ€์‚ฌ๊ฐ€ ์™„๋ฃŒ๋œ ๋‹จ์–ด๋Š” left์— ๋„ฃ์–ด์คŒ์œผ๋กœ์จ, ์•ŒํŒŒ๋ฒณ์ด ๋‘๊ฐœ ์ด์ƒ ๋“ฑ์žฅํ•˜๊ฒŒ ๋˜๋ฉด, ์ฒซ๋ฒˆ์งธ ๋“ฑ์žฅํ•œ ์ธ๋ฑ์Šค๊ฐ’์œผ๋กœ ๋“ค์–ด๊ฐ€๊ฒŒ๋” ์„ค์ •ํ•ด์ฃผ์—ˆ๋‹ค.
import Foundation

var line = Array(readLine()!)
var left: [Character] = []
var answer = [Int](repeating: -1, count: 26)

for i in 0..<line.count {
    let ch = line.removeFirst()
    if left.contains(ch) {
        continue
    }else {
        answer[Int(ch.asciiValue!)-97] = i
    }
    left.append(ch)
}

print(answer.map { "\($0)" }.joined(separator: " "))

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด

a ~ z ๊นŒ์ง€ ์•„์Šคํ‚ค ์ฝ”๋“œ๋กœ ๋ฐ”๊ฟ”์„œ i์— ๋„ฃ์–ด์ฃผ๊ณ  i๊ฐ’์„ ๋‹ค์‹œ ๋ฌธ์ž๋กœ ๋ฐ”๊ฟ”์„œ char์— ๋„ฃ์–ด์ค€๋‹ค. array s ์— char์ด ํฌํ•จ๋˜์–ด ์žˆ์œผ๋ฉด  s.index๋ฅผ ํ†ตํ•ด์„œ ๋ช‡๋ฒˆ์งธ์— ์žˆ๋Š”์ง€ ์ถœ๋ ฅํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰ํ–ˆ๋‹ค. ์•„์Šคํ‚ค์ฝ”๋“œ๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ์‹์€ ๋™์ผํ•˜์ง€๋งŒ, ์ด๋ฅผ ์ •๋‹ต๋ฐฐ์—ด์— ๋„ฃ์–ด์ฃผ๋Š” ๋ฐฉ์‹์—์„œ ์ฐจ์ด๊ฐ€ ์กฐ๊ธˆ ์žˆ์—ˆ๋‹ค.

let s = Array(readLine()!)
for i in Character("a").asciiValue!...Character("z").asciiValue! {
     var char = Character(UnicodeScalar(i))
    if s.contains(char){
        print("\(s.index(of: char)!)",terminator: " ")
    }else{
    print("-1", terminator: " ")
    }
}

 

๋ฐ˜์‘ํ˜•