Skip to content

Commit 6a7d258

Browse files
committed
Adds playground for Longest Common Subsequence
1 parent a6ddf98 commit 6a7d258

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
extension String {
2+
func longestCommonSubsequence(other:String) -> String {
3+
4+
func lcsLength(other: String) -> [[Int]] {
5+
var matrix = [[Int]](count:self.characters.count+1, repeatedValue:[Int](count:other.characters.count+1, repeatedValue:0))
6+
7+
for (i, selfChar) in self.characters.enumerate() {
8+
for (j, otherChar) in other.characters.enumerate() {
9+
if (otherChar == selfChar) {
10+
matrix[i+1][j+1] = (matrix[i][j]) + 1
11+
}
12+
else {
13+
matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j])
14+
}
15+
}
16+
}
17+
18+
return matrix;
19+
}
20+
21+
func backtrack(matrix: [[Int]]) -> String {
22+
var i = self.characters.count
23+
var j = other.characters.count
24+
var charInSequence = self.endIndex
25+
26+
var lcs = String()
27+
28+
while (i >= 1 && j >= 1) {
29+
if (matrix[i][j] == matrix[i][j - 1]) {
30+
j = j - 1
31+
}
32+
else if (matrix[i][j] == matrix[i - 1][j]) {
33+
i = i - 1
34+
charInSequence = charInSequence.predecessor()
35+
}
36+
else {
37+
i = i - 1
38+
j = j - 1
39+
charInSequence = charInSequence.predecessor()
40+
41+
lcs.append(self[charInSequence])
42+
}
43+
}
44+
45+
return String(lcs.characters.reverse());
46+
}
47+
48+
return backtrack(lcsLength(other))
49+
}
50+
}
51+
52+
// Examples
53+
54+
let a = "ABCBX"
55+
let b = "ABDCAB"
56+
let c = "KLMK"
57+
58+
a.longestCommonSubsequence(c) //""
59+
a.longestCommonSubsequence("") //""
60+
a.longestCommonSubsequence(b) //"ABCB"
61+
b.longestCommonSubsequence(a) //"ABCB"
62+
a.longestCommonSubsequence(a) // "ABCBX"
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Timeline
3+
version = "3.0">
4+
<TimelineItems>
5+
</TimelineItems>
6+
</Timeline>

0 commit comments

Comments
 (0)