func findReplaceString(_ S: String, _ indexes: [Int], _ sources: [String], _ targets: [String]) -> String {
var answer = [Character]()
var str = Array(S)
var index = 0
var i = 0
let offsets = indexes.enumerated().sorted(by: {$0.element < $1.element}).map {$0.offset}
let indexes = offsets.map {indexes[$0]}
let sources = offsets.map {sources[$0]}
let targets = offsets.map {targets[$0]}
while i < str.count {
if index >= indexes.count {
answer += Array(str[i...])
break
}
if i == indexes[index] {
if str.count - indexes[index] < sources[index].count {
index += 1
continue
}
var possible = true
for j in stride(from: 0, to: sources[index].count, by: 1) {
if str[i+j] != Array(sources[index])[j] {
possible = false
break
}
}
if possible {
answer.append(contentsOf:Array(targets[index]))
i += sources[index].count
}
index += 1
} else {
answer.append(str[i])
i += 1
}
}
return String(answer)
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme