最长公共子序列(Swift版本)

Posted KbDaVinci

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最长公共子序列(Swift版本)相关的知识,希望对你有一定的参考价值。

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)")
}

 

 

测试环境:https://swiftlang.ng.bluemix.net/#/repl

以上是关于最长公共子序列(Swift版本)的主要内容,如果未能解决你的问题,请参考以下文章

动态规划 最长公共子序列 过程图解

最长公共子序列(LCS),求LCS长度和打印输出LCS

最长公共子序列的应用

C语言实现最长公共子串与最长公共子序列

最长递增子序列 && 最大子序列最长递增子序列最长公共子串最长公共子序列字符串编辑距离

codevs 1862 最长公共子序列(求最长公共子序列长度并统计最长公共子序列的个数)