Created
April 18, 2011 11:57
-
-
Save oskimura/925192 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Lcs where | |
| import Data.Array | |
| makeTable xs ys = tbl | |
| where | |
| n = length xs | |
| m = length ys | |
| tbl :: Array (Int,Int) Integer | |
| tbl = array ((0,0),(n,m)) [let x = if (xs!!(i-1)) == (ys!!(j-1)) then 1 else 0 | |
| in ((i,j), if i==0 || j==0 then 0 else | |
| maximum [ tbl!(i-1, j-1) + x | |
| , tbl!(i-1, j) | |
| , tbl!(i, j-1) | |
| ] ) | |
| | (i,j) <- range((0,0),(n,m)) ] | |
| printLcs lcs xs ys = reverse . printLcs' n $ m | |
| where | |
| n = length xs | |
| m = length ys | |
| printLcs' 0 _ = "" | |
| printLcs' _ 0 = "" | |
| printLcs' i j | |
| | xs!!(i-1) == ys!!(j-1) = (xs!!(i-1)) : next | |
| | otherwise = if lcs!(i-1,j) >= lcs!(i,j-1) then printLcs' (i-1) j else printLcs' i (j-1) | |
| where next = printLcs' (i-1) (j-1) | |
| lcs xs ys = printLcs (makeTable xs $ ys) xs ys |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment