字符串中的有效括号(Haskell 实现)

Valid Parenthese in a string (Haskell implementation)

问题是检查字符串中的括号是否正确关闭。对于 Haskell 实施,到目前为止我有以下内容。看起来很别扭。我正在寻找更 "Haskell-style" 或更优雅的实现。

import Data.List

isValidParentheses :: String -> Bool
isValidParentheses = isValidHelper . (filter isParenthese)

getIndex :: (Eq a) => a -> [a] -> Int
getIndex c xs =  getOut (elemIndex c xs)
  where getOut (Just x) = x
        getOut Nothing = -1

isLeftParenthese :: Char -> Bool
isLeftParenthese c = (getIndex c "{[(") /= -1

isRightParenthese :: Char -> Bool
isRightParenthese c = (getIndex c "}])") /= -1

isParenthese :: Char -> Bool
isParenthese c = isLeftParenthese c || isRightParenthese c


isValidHelper :: String -> Bool
isValidHelper xs = helper xs []
  where helper (x:xs) []     | isRightParenthese x = False
                             | otherwise = helper xs [x]
        helper [] st = null st
        helper (x:xs) (s:ss) | isLeftParenthese x = helper xs (x:s:ss)
                              | ((getIndex x "}])") /= (getIndex s "{[(")) = False
                              | otherwise = helper xs ss

谢谢

  • 遍历字符串
  • 在堆栈中存储左括号
  • 将匹配的括号弹出堆栈
  • 最后检查栈是否为空

    isValid = loop []
      where
        match '(' ')' = True
        match '{' '}' = True
        match '[' ']' = True
        match  _   _  = False
    
        loop st [] = null st
        loop st (x:xs)
          | x `elem` "([{" = loop (x:st) xs
          | x `elem` ")]}" = case st of
            open : st' | match open x -> loop st' xs
            _ -> False -- unmatched close
          | otherwise = loop st xs