๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ฐ€์šด๋ฐ ๊ธ€์ž ๊ฐ€์ ธ์˜ค๊ธฐ Swift

by Fomagran ๐Ÿ’ป 2020. 2. 9.
728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ์„ค๋ช…

๋‹จ์–ด s์˜ ๊ฐ€์šด๋ฐ ๊ธ€์ž๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ๋งŒ๋“ค์–ด ๋ณด์„ธ์š”. ๋‹จ์–ด์˜ ๊ธธ์ด๊ฐ€ ์ง์ˆ˜๋ผ๋ฉด ๊ฐ€์šด๋ฐ ๋‘๊ธ€์ž๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์žฌํ•œ์‚ฌํ•ญ

  • s๋Š” ๊ธธ์ด๊ฐ€ 1 ์ด์ƒ, 100์ดํ•˜์ธ ์ŠคํŠธ๋ง์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ

s return
abcde c
qwer we

ํ•ต์‹ฌ:๋„ˆ ๋ฌธ์ž์—ด ์ค‘์— index์ฐพ์•„์„œ ๋บ„ ์ˆ˜ ์žˆ์–ด?

ํ’€์ด: String์˜ index๋ฒˆ์งธ ๋ฌธ์ž๋ฅผ ๋นผ๋ ค๋ฉด ๋‹จ์ˆœํžˆ s[1]ํ•˜๋ฉด ์˜ค๋ฅ˜๊ฐ€ ๋‚œ๋‹ค.

String.startIndex๋ฅผ ์•Œ์•„๋‚ด์–ด์„œ s[s.startInex]๋ฅผ ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

๋˜ํ•œ ์–ด๋””์„œ๋ถ€ํ„ฐ ์–ด๋””๊นŒ์ง€๋ผ๋Š” ๋ฉ”์†Œ๋“œ๋Š” String.index[์–ด๋””์„œ๋ถ€ํ„ฐ,offsetBy:์–ด๋””๊นŒ์ง€) ์–ด๋””๊นŒ์ง€๋ผ๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๋Š” offsetBy์ด๋‹ค. startIndex๋ถ€ํ„ฐ offsetBy๊นŒ์ง€ ์•Œ๋ ค์ค˜๋ผ๋Š” ๋œป์ด๋‹ค.

์ด ๋ฌธ์ œ์—์„œ๋Š” ๊ฐ€์šด๋ฐ ์ธ๋ฑ์Šค๋งŒ ์•Œ์•„๋‚ด๋ฉด ๋˜๋ฏ€๋กœ ์ง์ˆ˜ ์ผ๋• 2๋กœ ๋‚˜๋ˆด์„ ๋•Œ ๊ฐ’๊ณผ -1ํ•œ ๊ฐ’์ด ํ•„์š”ํ•˜๊ณ (0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฏ€๋กœ)

ํ™€์ˆ˜์ผ ๋• 2๋กœ ๋‚˜๋ˆด์„ ๋•Œ ๊ฐ’๋งŒ ํ•„์š”ํ•˜๋‹ค.

๊ทธ๋Ÿฌ๋ฏ€๋กœ s[s.index(s.startIndex, offsetBy:  s.count/2 - 1)] ๋Š” ๋ฌธ์ž์—ด[๋ฌธ์ž์—ด.index[์‹œ์ž‘,offsetBy: ๋ฌธ์ž์—ด์ด ๊ฐ€์šด๋ฐ ๊ฐ’)]์„ ํ•ด์ฃผ๋ฉด ๊ฐ€์šด๋ฐ ๋ฌธ์ž๋ฅผ ์•Œ ์ˆ˜ ์žˆ๋‹ค. ๋ฌธ์ž๋Š” return์ด ์•ˆ๋˜๋ฏ€๋กœ "\(๋ฌธ์ž)"๋ฅผ ํ•ด์ค€๋‹ค.

 

1
2
3
4
5
6
7
8
9
10
import Foundation
 
 
func solution(_ s:String-> String {
    if s.count%2 == 0{
        return "\(s[s.index(s.startIndex, offsetBy:  s.count/2 - 1)])\(s[s.index(s.startIndex, offsetBy: s.count/2)])"
    }
        return "\(s[s.index(s.startIndex, offsetBy:  s.count/2)])"
    
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

https://roeldowney.tistory.com/90 ์ด ๋ถ„ ๋ธ”๋กœ๊ทธ ์ฐธ์กฐ

์‚ฌ์‹ค ๊ทธ๋ƒฅ ๋ฌธ์ž์—ด ์ž์ฒด๋ฅผ ๋ฐฐ์—ด์— ๋„ฃ๊ณ  ๊ฑฐ๊ธฐ์— ์นด์šดํŠธ๋งŒ ๋„ฃ์–ด์ฃผ๋ฉด ๋๋‹ค....

1
2
3
4
5
6
7
8
9
import Foundation
 
 
func solution(_ s:String-> String {
    if Array(s).count % 2 == 0{
        return String(Array(s)[s.count/2 - 1...(s.count/2)])
    }
    return String(Array(s)[s.count/2])
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€