最长公共子序列(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

posted @ 2017-02-04 11:09  KbDaVinci  阅读(191)  评论(0编辑  收藏  举报