[Swift] 프로그래머스 - 문자열 겹쳐쓰기 / LV.0, 181943
https://school.programmers.co.kr/learn/courses/30/lessons/181943
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
항상 문제 해석이 젤 어려운거 같네요 ㅜ
빨간색으로 바꿔야할 위치를 표시해뒀어요 !
my_string He11oWor1d 10자
overwrite_string lloWorl 7자
s 2
my_string Program29b8UYP 14자
overwrite_string merS123 7자
s 7
1. String에 로 subscript[Int]로 접근할 수 없다. String.Index로 접근해야한다.
2. String.Index, index 관련 메소드들을 알고있어야한다.
입력 받은 String.Index i로부터 distance 만큼 떨어진 index offset(위치)를 String.Index 으로 반환해줘요.
여기서 특이점은 distance가 양수라면 index(after:), 음수라면 index(before:)에 대한 abs(distance)와 같은 결과라고해요.
안 보고가면 섭섭해요
index(after:), index(before:) 두 메소드 모두 별 차이는 없네요
입력 예 첫 번째로 예시를 들어볼게요.
let frontIdx = my_string.index(my_string.startIndex, offsetBy: s - 1) // s: 2
let afterIdx = my_string.index(after: my_string.startIndex)
print("is same ? \(frontIdx == afterIdx)")
distance가 1이었기에 쉬웠다.
distance가 3이라면 어떨까 ? index(after:) 도 공평하게 3번 호출해줘야할거같다 ...!
let frontIdx = my_string.index(my_string.startIndex, offsetBy: s - 1) // s: 4
let afterIdx = my_string.index(after: my_string.startIndex)
let afterIdx2 = my_string.index(after: afterIdx)
let afterIdx3 = my_string.index(after: afterIdx2)
print("is same ? \(frontIdx == afterIdx3)")
import Foundation
func solution(_ my_string:String, _ overwrite_string:String, _ s:Int) -> String {
var result = ""
if s != 0 {
let frontIdx = my_string.index(my_string.startIndex, offsetBy: s - 1)
result.append(String(my_string[...frontIdx]))
}
result.append(overwrite_string)
let idx = overwrite_string.count - my_string.count + s
if idx != 0 {
let backIdx = my_string.index(my_string.endIndex, offsetBy: idx)
result.append(String(my_string[backIdx...]))
}
return result
}
https://developer.apple.com/documentation/swift/string/index(_:offsetby:)
index(_:offsetBy:) | Apple Developer Documentation
Returns an index that is the specified distance from the given index.
developer.apple.com
https://developer.apple.com/documentation/swift/string/index(after:)
index(after:) | Apple Developer Documentation
Returns the position immediately after the given index.
developer.apple.com
https://velog.io/@ji-yeon224/프로그래머스-문자열-겹쳐쓰기-swift