我不知道我的代碼有什么問題。我可以得到一些幫助來理解它嗎?
使用longestChain 查看文本中最長的字串由相同字符組成的長度!
Examples:
longestChain "2111234" == 3
longestChain "0023212212222" == 4
longestChain "23232323232" == 1
longestChain " !!!-------" == 7
longestChain :: String -> Int
longestChain (x:y:xs)
| x == y = 1 longestChain xs
| otherwise = longestChain (y:xs)
uj5u.com熱心網友回復:
> :m Data.List
Data.List> maximum $ map length $ group $ " !!!-------"
7
group :: Eq a => [a] -> [[a]]在Data.List.
“ group 函式接受一個串列并回傳一個串列串列,使得結果的串聯等于引數。此外,結果中的每個子串列只包含相等的元素。“
map length 回傳一個串列,其中每個子串列都由其長度替換。
maximum 回傳這些長度的最大值。
我是怎么找到的group?我在Hoogle中搜索了具有該簽名的函式。
uj5u.com熱心網友回復:
更多 @user1984 回答的風格。我仍然會說這段代碼難以閱讀/令人困惑。
longestChain :: String -> Int
longestChain xs = go xs 0 where
go [] curr = curr
go [x] curr = curr 1
go (x:y:xs) curr | x == y = go (y:xs) (curr 1)
| otherwise = max (curr 1) (go (y:xs) 0)
(這里go [] curr = ...需要分支,因為longestChain可能已將空字串傳遞給go.)
curr總是計算“欠款”,因此如果在字串末尾go出現單例[x],則必須是當前鏈的最后一個字符,請增加長度。
如果go找到相鄰的相同 Chars x == y,則為 加 1 x,在尾部遞回。
如果go發現相鄰的不同字符otherwise,仍然為x(它是當前鏈的最后一個字符)加1 ;開始一個新的尾部計數。從尾部回傳max遞增的currcp 的max。
測驗:
Main> longestChain ""
0
Main> longestChain "a"
1
Main> longestChain "Mississippi"
2
Main> longestChain " !!!-------"
7
Main> longestChain " !!!-------*"
7
uj5u.com熱心網友回復:
這不干凈,但它有效。
longestChain :: String -> Int
longestChain [] = 0
longestChain xs = go xs 0 1 where
go [] curr res = res
go [x] curr res
| curr > 0 = max (curr 1) res
| otherwise = res
go (x:y:xs) curr res
| x == y = go (y:xs) (curr 1) (max (curr 1) res)
| curr > 0 = go (y:xs) 0 (max (curr 1) res)
| otherwise = go (y:xs) 0 res
當我們找到相似的字符時,在函式的結果上加一個是不夠的。我們需要計算字串中的每個鏈并回傳我們找到的最長長度。這就是curr和res照顧。
此外,當您發現 2 個字符匹配時,您需要將第二個添加到您的串列中以將其與下一個匹配,否則您會錯過一個。另外,當你發現一個不匹配的時候,如果你有你的curr大于0,就說明這個字符屬于上一個鏈的末端,所以你加一個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/347702.html
下一篇:Control.Monad.Reader.withReader實際上是Data.Functor.Contravariant.contramap嗎?
