-
Notifications
You must be signed in to change notification settings - Fork 1
/
Contents.swift
58 lines (47 loc) · 1.26 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//: Playground - noun: a place where people can play
import UIKit
// Hack convention
// Don't mess up with Range from Swift 3
extension String {
func charAt(_ i: Int) -> String {
return String((self as NSString).character(at: i))
}
}
/////////////////////////////
// NAIVE APPROACH
/////////////////////////////
// Recurvise func to length of LCS
func LCS(_ a: String, _ b: String) -> Int{
// Exit
if a.characters.count
== 0 || b.characters.count == 0 {
return 0
}
// Prepare
let lengthA = a.characters.count
let lengthB = b.characters.count
let aIndex = a.index(a.endIndex, offsetBy: -1)
let bIndex = b.index(b.endIndex, offsetBy: -1)
// Sub-problem
if a.charAt(lengthA - 1) == b.charAt(lengthB - 1) {
// MATCH
return 1 + LCS(a.substring(to: aIndex), b.substring(to: bIndex))
} else {
// NOT MATCH
return max(LCS(a.substring(to: aIndex), b), LCS(a, b.substring(to: bIndex)))
}
}
// Test
let a = "acbaed"
let b = "abcadf"
print(LCS(a, b))
// Unicode
let x = "😇🙌😉💰🎹"
let y = "🙌🍒💰✈️🎹😎🔴"
print(LCS(x, y))
extension String {
func `subscript`(range: ClosedRange) -> String {
return "abc"
}
}
let sub = a[0..1]