为了好玩,您可以在从结尾开始迭代第一个序列时使用start with predicate,如下所示:
let first: [String] = ["A", "B", "F", "E"]
let second: [String] = ["F", "E", "A", "G"]
var pos = first.endIndex
while pos > first.startIndex,
second.starts(with: first[pos...], by: { $0 != $1}),
!second.isEmpty {
first.formIndex(before: &pos)
}
let result = first[..<pos] + second // ["A", "B", "F", "E", "A", "G"]
这将产生一个子序列,在本例中是一个数组切片.如果需要数组,只需显式设置结果类型:
let result: [String] = first[..<pos] + second
根据OP注释,如果需要成对匹配子序列,只需每隔两个元素进行偏移:
let first = "ABFF"
let second = "FFAG"
var pos = first.endIndex
while pos > first.startIndex,
second.starts(with: first[pos...], by: { $0 != $1 }),
!second.isEmpty {
first.formIndex(&pos, offsetBy: -2)
}
let result: String = first[..<pos] + second // "ABFFAG"
如果需要用空格分隔的字符串元素:
var first = "A B C D E F G D E"
var second = "D E F C B A"
first.removeAll(where: \.isWhitespace)
second.removeAll(where: \.isWhitespace)
var pos = first.endIndex
while pos > first.startIndex,
second.starts(with: first[pos...], by: { $0 != $1 }),
!second.isEmpty {
first.formIndex(&pos, offsetBy: -2)
}
let result = (first[..<pos] + second)
.map(String.init)
.joined(separator: " ")
result // "A B C D E F G D E F C B A"
编辑/更新:
按照上一次 comments /回答中显示的逻辑,您可以执行以下操作:
extension RangeReplaceableCollection where Element: Equatable {
mutating func appendAndMerge<C: Collection>(with collection: C) where C.Element == Element {
var lowerBound = startIndex
formIndex(&lowerBound, offsetBy: Swift.min(count, count-collection.count), limitedBy: endIndex)
while !collection.starts(with: self[lowerBound...]) {
formIndex(&lowerBound, offsetBy: 1, limitedBy: endIndex)
}
replaceSubrange(lowerBound..., with: collection)
}
}
用法:
var first = ["at", "by", "chicken", "dog", "eat", "for", "good", "dog", "eat"]
let second = ["good", "dog", "eat", "feed", "cats", "bonk", "atrophe"]
first.appendAndMerge(with: second)
print(first)
这会打印出来
["at","by","chicken","dog","eat","for","good","dog","eat","feed","cats","bonk","atrophy"]
使用字符串(字符集合)
var first = "at by chicken dog eat for good dog eat"
let second = "good dog eat feed cats bonk atrophe"
first.appendAndMerge(with: second)
print(first)
这会打印出来:
"由鸡、狗、吃为好、狗、吃为食、cat 、邦克阿托弗"