2022. 10. 21. 14:09ใํ๋ก๊ทธ๋๋จธ์ค-Swift
ํ๋ก๊ทธ๋๋จธ์ค - ํ์ผ๋ช ์ ๋ ฌ(Swift)
๋ฌธ์ ์ค๋ช
https://school.programmers.co.kr/learn/courses/30/lessons/17686
๋์ ํ์ด
numFlag์ tailFalg๋ณ์๋ฅผ ํตํด์ ๋ฐฐ์ด์ ์ชผ๊ฐฐ์ง๋ง ๋ณ๋ก ์ข์๋ฐฉ๋ฒ์ ์๋ ๊ฒ ๊ฐ๋ค.
๊ทธ๋ฆฌ๊ณ ์ ๋ ฌ์ ํ ๋ ์ฒ์์๋ ์ผํญ์ฐ์ฐ์ ์์ $0.head < $1.head ? $0.head < $1.head : ๋๋จธ์ง๋ก์ง ์ด๋ฐ์์ผ๋ก ์์ฑํ๋๋ฐ ์ด๋ ์ฒซ๋ฒ์งธ $0.head < $1.head๋ ๋จ์ํ ์์๊ฒ์ด ๋ค์๊ฒ๋ณด๋ค ํฌ๋ค๋ฉด ์ด๊ธฐ ๋๋ฌธ์ ์ด๋ ๊ฒ ํ๋ฉด ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ๊ตฌํ์ง์์์ !=์ผ๋ก ๋ฐ๊ฟ์ฃผ์๋ค.
struct Image {
let head: String
let number: String
let tail: String
}
func solution(_ files:[String]) -> [String] {
var images: [Image] = []
for file in files {
var numFlag = false
var tailFlag = false
var head: String = ""
var num: String = ""
var tail: String = ""
let arr = Array(file)
for x in arr {
if !x.isNumber && !numFlag {
head += String(x)
} else if x.isNumber && !tailFlag {
numFlag = true
num += String(x)
} else {
tail += String(x)
tailFlag = true
}
}
let image = Image(head: head, number: num, tail: tail)
images.append(image)
}
let b = images.sorted { $0.head.lowercased() != $1.head.lowercased() ? $0.head.lowercased() < $1.head.lowercased() : Int($0.number)! < Int($1.number)! }
return b.map{
let str = $0.head + String($0.number) + $0.tail
return str
}
}
๋ค๋ฅธ ์ฌ๋์ ํ์ด
prefix(while:) ๊ณผ drop(while:)์ ์ฌ์ฉํด์ ๋ฌธ์ ๋ฅผ ํ์๋ค.
prefix(while:)์ ์กฐ๊ฑด์ด true์ธ ๋์์ prefix๋ฅผ ๊ฐ์ ธ์ค๋ ๊ฒ์ด๋ค. ์ฆ ์กฐ๊ฑด์ด false๊ฐ ๋๋ฉด prefix๊ฐ ๋ฉ์ถ๋ค.
drop(while:)์ ์กฐ๊ฑด์ด true์ผ๋ ๊ฐ๋ค์ ์ง์ฐ๊ณ false๊ฐ ๋๋ ์๊ฐ ๊ทธ ๋ค์ ๊ฐ๋ค์ ์กฐ๊ฑด์ ๊ฑธ๋ฆฌ์ง ์๊ณ ์ ์ฒด๋ฅผ ๋ฆฌํดํ๋ค.
์ฆ
let str = "foo010bar020.zip"๋ผ๋ ๋ฌธ์์ด์ด ์์๋ foo๋ฅผ ์ง์ฐ๊ณ 010bar020.zip์ด ๋ฆฌํด๋๋ ๊ฒ์ด๋ค.
๊ทธ๋ฆฌ๊ณ sortํ๋ ๋ถ๋ถ์์๋ head์ ์ด๋ฆ๋ ๊ฐ๊ณ number์ ์ด๋ฆ๋ ๊ฐ์ ๋๋ false๋ฅผ ์คฌ๋๋ฐ ์ด์ ๋ ์ ๋ ฅ๊ฐ ์์๋๋ก ๋ฆฌํด์ ํ๋ฉด ๋๊ธฐ ๋๋ฌธ์ด๋ค. ๊ทธ๋์ ์ซ์๋ฅผ ๋ฐ๊พธ์ง ์๋๋ก ํ๋ค.
struct Word {
let head: String
let number: String
let index: Int
}
func makeWord(_ str: String, _ idx: Int) -> Word {
let head = str.prefix{ !$0.isNumber }.lowercased()
let num = str.drop{ !$0.isNumber }.prefix{ $0.isNumber }
return Word(head: head, number: String(num), index: idx)
}
func AsortB(_ lhs: Word, _ rhs: Word) -> Bool {
let aNum = Int(lhs.number)!, bNum = Int(rhs.number)!
if lhs.head != rhs.head { return lhs.head < rhs.head }
if aNum != bNum { return aNum < bNum }
return false
}
func solution(_ files:[String]) -> [String] {
var words: [Word] = []
for (i, file) in files.enumerated() {
words.append(makeWord(file, i))
}
words.sort { AsortB($0, $1) }
let result = words.map{ files[$0.index] }
return result
}
'ํ๋ก๊ทธ๋๋จธ์ค-Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค - 2๊ฐ ์ดํ๋ก ๋ค๋ฅธ ๋นํธ (1) | 2022.10.22 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค - ๋ชจ์์ฌ์ (Swift) (0) | 2022.10.21 |
ํ๋ก๊ทธ๋๋จธ์ค - ๋ฐฉ๋ฌธ ๊ธธ์ด(Swift) (0) | 2022.10.20 |
ํ๋ก๊ทธ๋๋จธ์ค - ์คํฌํธ๋ฆฌ(Swift) (0) | 2022.10.20 |
ํ๋ก๊ทธ๋๋จธ์ค - ์ฐ์ ๋ถ๋ถ ์์ด ํฉ์ ๊ฐ์ (0) | 2022.10.20 |