2011年6月9日 星期四

最長共同子序列



給2 個字串,請你輸出他們的最長共同子序列(longest common subsequence)的長度。
也就是說,在這兩個字串各自所有的子序列之中,內容相同而且長度最長的那個子序列。舉
例來說有兩個字串abcdgh 和aedfhr,它們的最長共同子序列為adh,長度為3。
輸入說明:
輸入檔含有多筆測試資料,每筆測試資料為二行字串,每行最多有 1000 個字元。
輸出說明:
對輸入的每筆測試資料,輸出它們最長共同子序列的長度。
輸入範例:
a1b2c3d4e
zz1yy2xx3ww4vv
abcdgh
aedfhr
輸出範例:
4
3

4 則留言:

  1. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2

    Do While Not EOF(1)
    Input #1, X1
    Input #1, X2
    ans = 0

    For i = 1 To Len(X1)
    For ii = 1 To Len(X2)
    If Mid(X1, i, 1) = Mid(X2, ii, 1) Then ans = ans + 1: Exit For
    Next
    Next

    Print #2, ans
    Loop

    Close
    Close
    End
    End Sub

    回覆刪除
  2. Private Sub Form_Load()
    Dim Times As Byte
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do While Not EOF(1)
    Input #1, X
    Input #1, Y
    Times = 0

    For i = 1 To Len(X)
    For j = 1 To Len(Y)
    If Mid(X, i, 1) = Mid(Y, j, 1) Then Times = Times + 1 : Exit For
    Next j
    Next i

    Print #2, Times
    Loop
    Close #2
    Close #1



    End
    End Sub

    輸入:
    ABBBBBBBBBCC
    ADDDCCCBBBBB
    gsadfjklasjf
    askdrjtuihjklsd
    輸出:

    12
    9

    回覆刪除
  3. Dim m As String, n As String
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\out.txt" For Output As #2
    Open App.Path & "\in.txt" For Input As #1

    Do While Not EOF(1)
    c = 0: List1.Clear: List2.Clear
    Input #1, m, n
    For i = 1 To Len(m)
    a = Mid(m, i, 1)
    List1.AddItem a
    Next
    For i = 1 To Len(n)
    b = Mid(n, i, 1)
    List2.AddItem b
    Next
    For i = 0 To List1.ListCount - 1
    For j = 0 To List2.ListCount - 1
    If List1.List(i) = List2.List(j) Then
    List2.List(j) = ""
    c = c + 1
    GoTo ne
    End If
    Next
    ne:
    Next
    Print #2, c
    Loop
    Close #1
    Close #2
    End
    End Sub
    ----------------------------
    in.txt
    a1b2c3d4e
    zz1yy2xx3ww4vv
    abcdgh
    aedfhr
    ABBBBBBBBBCC
    ADDDCCCBBBBB
    -----------------------
    out.txt
    4
    3
    12

    回覆刪除
  4. 這題,你們三個都錯吧?
    去看看舊題目的地方。

    回覆刪除