Haskell - 函数检查括号内的平衡

时间:2014-02-09 15:06:19

标签: haskell

我必须在Haskell中编写一个函数来检查包含开括号和闭括号的字符串是否平衡。对于每个打开的括号,必须有一个关闭,空字符串也被认为是平衡的。

Ex. (()) is balanced
(())) is not balanced.
()(()) is balanced.
()(())) is not balanced.

由于

2 个答案:

答案 0 :(得分:6)

一般来说,算一算。如果你看到a增加(如果你看到a则递减)。如果计数在任何地方变为负数或在结束时不为零,那么你注定要失败。否则它是平衡的。

答案 1 :(得分:0)

经过测试的功能,它运行正常:

module Main where
import Data.List

balanced s = length(removePairs s) == 0
 where removePairs []    = []
       removePairs (x:xs)
        | x == '('       = removePairs (removeLast xs 0)
        | (x:xs) == ")"  = "."
        | x == ')'       = xs
        | x == '.'       = (x:xs)
       removeLast []  _  = "."
       removeLast xs n
        | ')' `notElem` xs  = ")"
        | (xs!!n) == ')'    = (fst splitted)++(tail $ snd splitted)
        | length xs == n    = ")"
        | otherwise         = removeLast xs (n+1)
        where splitted      = splitAt n xs

main = print $ balanced "()()()(())" -- prints True

codepad.org