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

[Swift Algorithm] ์„œ์šธ์—์„œ ๊น€์„œ๋ฐฉ ์ฐพ๊ธฐ Programmers(Lv.1)

by seolhee2750 2021. 6. 17.
๋ฌธ์ œ ์„ค๋ช…

Stringํ˜• ๋ฐฐ์—ด seoul์˜ element์ค‘ "Kim"์˜ ์œ„์น˜ x๋ฅผ ์ฐพ์•„, "๊น€์„œ๋ฐฉ์€ x์— ์žˆ๋‹ค"๋Š” String์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•˜์„ธ์š”. seoul์— "Kim"์€ ์˜ค์ง ํ•œ ๋ฒˆ๋งŒ ๋‚˜ํƒ€๋‚˜๋ฉฐ ์ž˜๋ชป๋œ ๊ฐ’์ด ์ž…๋ ฅ๋˜๋Š” ๊ฒฝ์šฐ๋Š” ์—†์Šต๋‹ˆ๋‹ค.

 

์ œํ•œ ์กฐ๊ฑด
  • seoul์€ ๊ธธ์ด 1 ์ด์ƒ, 1000 ์ดํ•˜์ธ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
  • seoul์˜ ์›์†Œ๋Š” ๊ธธ์ด 1 ์ด์ƒ, 20 ์ดํ•˜์ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค.
  • "Kim"์€ ๋ฐ˜๋“œ์‹œ seoul ์•ˆ์— ํฌํ•จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
seoul return
["Jane", "Kim"] "๊น€์„œ๋ฐฉ์€ 1์— ์žˆ๋‹ค"

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ seoul:[String]) -> String {
    return "๊น€์„œ๋ฐฉ์€ \(seoul.firstIndex(of: "Kim")!)์— ์žˆ๋‹ค."
}
  • ๋ฌธ์ž์—ด ์•ˆ์— \๋ฅผ ์ด์šฉ, firstIndex ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ”๋กœ ๋ฆฌํ„ดํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์‰ฌ์šด ๋ฌธ์ œ์˜€๊ณ , \๋ฅผ ์ด์šฉํ•œ ๋ฌธ์ž์—ด ์‚ฝ์ž…๊ณผ firstIndex ํ•จ์ˆ˜, ๊ทธ๋ฆฌ๊ณ  firstIndex๋Š” ์˜ต์…”๋„ ํƒ€์ž…์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ•์ œ ์ถ”์ถœ์„ ํ•ด์ค˜์•ผ ํ•œ๋‹ค๋Š” ์ ๋งŒ ์•Œ๊ณ  ์žˆ๋‹ค๋ฉด ๋ฌธ์ œ์—†๋Š” ๊ฒƒ,,!์ด์—ˆ๋‹ค.

 


 

๐Ÿ– [ ์ถ”๊ฐ€ ] 1์ฃผ์ผ ํ›„ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ

func solution(_ seoul:[String]) -> String {
    return "๊น€์„œ๋ฐฉ์€ " + String(seoul.firstIndex(of: "Kim")!) + "์— ์žˆ๋‹ค"
}
  • + ์—ฐ์‚ฐ์ž๋กœ ๋ฌธ์ž์—ด๋“ค์„ ๋ถ™์—ฌ์„œ ์ถœ๋ ฅํ•ด์ฃผ์—ˆ๋‹ค. 
  • ์ €๋ฒˆ ์ฃผ์™€ ๋‹ค๋ฅธ ์ ์€ ๋”ฑํžˆ ์—†๊ณ , \๋Œ€์‹  +๋กœ ๋ถ™์—ฌ์ค€ ๊ฒƒ์ด ์ฐจ์ด์ ,,!

 


 

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/12919

 

๋Œ“๊ธ€