프로그래머스 (Swift)/기초
[Day3-1] 문자열 섞기
은더기
2024. 1. 21. 16:21
문제
내 정답 코드
import Foundation
func solution(_ str1:String, _ str2:String) -> String {
let count = str1.count + str2.count
var result = ""
var num1 = 0
var num2 = 0
for i in 0..<count {
if i % 2 == 0 {
result += String(str1[str1.index(str1.startIndex, offsetBy: num1)])
num1 += 1
} else {
result += String(str2[str2.index(str2.startIndex, offsetBy: num2)])
num2 += 1
}
}
return result
}
#
1. 두개의 문자열의 카운트를 가져와 합하고 그 만큼의 반복문을 수행한다.
2. 짝수번째 문자는 str1의 문자를 홀수번째 문자는 str2의 문자를 가져온다.
3. num변수를 통해 각 str1, str2의 몇번째 문자를 가져올지 판단한다.
-> 코드 개선
아래와 같이 반복문이 돌아가는 횟수를 줄이고 쓸데 없는 변수를 통해 다시 짜보았다.
import Foundation
func solution(_ str1:String, _ str2:String) -> String {
let count = str1.count + str2.count
var result = ""
for i in 0..<str1.count {
result += String(str1[str1.index(str1.startIndex, offsetBy: i)])
result += String(str2[str2.index(str2.startIndex, offsetBy: i)])
}
return result
}
배운 기술
1. string.index 복습