RosettaCodeData/Task/Longest-common-subsequence/Swift/longest-common-subsequence-2.swift

34 lines
921 B
Swift
Raw Permalink Normal View History

2020-02-17 23:21:07 -08:00
func lcs(_ s1: String, _ s2: String) -> String {
var lens = Array(
repeating:Array(repeating: 0, count: s2.count + 1),
count: s1.count + 1
)
2016-12-05 23:44:36 +01:00
2020-02-17 23:21:07 -08:00
for i in 0..<s1.count {
for j in 0..<s2.count {
if s1[s1.index(s1.startIndex, offsetBy: i)] == s2[s2.index(s2.startIndex, offsetBy: j)] {
2016-12-05 23:44:36 +01:00
lens[i + 1][j + 1] = lens[i][j] + 1
} else {
lens[i + 1][j + 1] = max(lens[i + 1][j], lens[i][j + 1])
}
}
}
2020-02-17 23:21:07 -08:00
var returnStr = ""
var x = s1.count
var y = s2.count
2016-12-05 23:44:36 +01:00
while x != 0 && y != 0 {
if lens[x][y] == lens[x - 1][y] {
2020-02-17 23:21:07 -08:00
x -= 1
2016-12-05 23:44:36 +01:00
} else if lens[x][y] == lens[x][y - 1] {
2020-02-17 23:21:07 -08:00
y -= 1
2016-12-05 23:44:36 +01:00
} else {
2020-02-17 23:21:07 -08:00
returnStr += String(s1[s1.index(s1.startIndex, offsetBy: x - 1)])
x -= 1
y -= 1
2016-12-05 23:44:36 +01:00
}
}
2020-02-17 23:21:07 -08:00
return String(returnStr.reversed())
2016-12-05 23:44:36 +01:00
}