在数组中查找连续的元素序列
Find contiguous sequence of elements in an array
经过研究,我只找到了获取数组中不连续元素序列的方法。
我想知道是否有一种有效的方法可以使用 Swift.
获取数组中所有连续的元素序列
示例:
对于 [1, 2, 3]
,答案是
1
1 2
1 2 3
2
2 3
3
只需使用两个带有列表切片的循环来获取所有连续的子序列。
let arr = [1,2,3,4]
var res = [[Int]]()
for i in 0..<arr.count {
for j in i..<arr.count {
res.append(Array(arr[i...j]))
}
}
print(res)
// [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
使用函数式方法,解决方案类似于:
let numbers = [1,2,3,4]
let contiguousSubsequences = numbers.indices.flatMap { lowerBound in
numbers[lowerBound...].indices.map { numbers[lowerBound...[=10=]] }
}
contiguousSubsequences // [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
您还可以制作一个通用的计算 属性 扩展集合协议,允许您将它用于任何类型的集合,包括字符串和子序列:
extension Collection {
var contiguousSubsequences: [SubSequence] {
indices.flatMap { lowerBound in
self[lowerBound...].indices.map { self[lowerBound...[=11=]] }
}
}
}
用法:
let numbers = [1,2,3,4]
let contiguousSubsequences = numbers.contiguousSubsequences
contiguousSubsequences // [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
let letters = "abcd"
let contiguousSubstrings = letters.contiguousSubsequences
contiguousSubstrings // ["a", "ab", "abc", "abcd", "b", "bc", "bcd", "c", "cd", "d"]
经过研究,我只找到了获取数组中不连续元素序列的方法。 我想知道是否有一种有效的方法可以使用 Swift.
获取数组中所有连续的元素序列示例:
对于 [1, 2, 3]
,答案是
1
1 2
1 2 3
2
2 3
3
只需使用两个带有列表切片的循环来获取所有连续的子序列。
let arr = [1,2,3,4]
var res = [[Int]]()
for i in 0..<arr.count {
for j in i..<arr.count {
res.append(Array(arr[i...j]))
}
}
print(res)
// [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
使用函数式方法,解决方案类似于:
let numbers = [1,2,3,4]
let contiguousSubsequences = numbers.indices.flatMap { lowerBound in
numbers[lowerBound...].indices.map { numbers[lowerBound...[=10=]] }
}
contiguousSubsequences // [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
您还可以制作一个通用的计算 属性 扩展集合协议,允许您将它用于任何类型的集合,包括字符串和子序列:
extension Collection {
var contiguousSubsequences: [SubSequence] {
indices.flatMap { lowerBound in
self[lowerBound...].indices.map { self[lowerBound...[=11=]] }
}
}
}
用法:
let numbers = [1,2,3,4]
let contiguousSubsequences = numbers.contiguousSubsequences
contiguousSubsequences // [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
let letters = "abcd"
let contiguousSubstrings = letters.contiguousSubsequences
contiguousSubstrings // ["a", "ab", "abc", "abcd", "b", "bc", "bcd", "c", "cd", "d"]