Maximum common sub-sequence (Swift version)

Source: Internet
Author: User

Class Mark {
var count:int
var type:int

Init (Count:int, Type:int) {
Self.count = Count
Self.type = Type
}
}

Func Findlcs (_ List1: [Character], _ List2: [Character]), [Character] {
For C in List1 {
Print ("List1 = \ (c)")
}

For C in List2 {
Print ("List2 = \ (c)")
}

Let M = List1.count

Let n = List2.count

var marks = [Mark] ()

For _ in 1...m*n {
Marks.append (Mark (count:0, type:0))
}

For I in 0...m-1 {
For J in 0...n-1 {
var mark = Marks[i*n + j]

If list1[i] = = List2[j] {

Mark.type = 2

Print ("Got a Equable")

If i = = 0 | | j = = 0 {
Mark.count = 1
} else {
Let _mark = marks[(i-1) *n + (j-1)]
Mark.count = _mark.count + 1
}
} else {

Let Mark1 = i > 0? marks[(i-1) *n + j]: Marks[j]
Let Mark2 = j > 0? Marks[i*n + (j-1)]: Marks[i*n]

If Mark1.count >= mark2.count {
Mark.type = 1
Mark.count = Mark1.count
} else {
Mark.count = Mark2.count
}
}
}
}

For Mark in marks {
Print ("Mark ' s count = \ (mark.count), mark ' s type = \ (Mark.type)")
//     }

var characters = [Character] ()

Func Printlcs (_ List: [Character], _ I:int, _ J:int) {
If i < 0 | | J < 0 {
Return
}

Let type = Marks[i*n+j].type

if type = = 2 {
Printlcs (list, i-1, j-1)
Characters.append (List[i])
} else if type = = 1 {
Printlcs (list, i-1, J)
} else {
Printlcs (list, I, j-1)
}
}

Printlcs (List1, list1.count-1, list2.count-1)

return characters
}

Let List1 = "ABCDEF"

Let List2 = "BDCEFG"

Let characters = Findlcs (Array (list1.characters), Array (list2.characters))

For C in characters {
Print ("\ (c)")
}

Test environment: HTTPS://SWIFTLANG.NG.BLUEMIX.NET/#/REPL

Maximum common sub-sequence (Swift version)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.