Skip to content

Commit

Permalink
fix bracket sequence checker
Browse files Browse the repository at this point in the history
  • Loading branch information
kazbekovruslan committed May 29, 2024
1 parent c76e43f commit 99f7264
Showing 1 changed file with 39 additions and 29 deletions.
68 changes: 39 additions & 29 deletions Homework4/BracketSequence/BracketSequence.fs
Original file line number Diff line number Diff line change
@@ -1,32 +1,42 @@
module BracketSequence

let braces = [ ('(', ')'); ('[', ']'); ('{', '}') ]

// without another declaring braces in function I have nullReferenceException
let isOpeningBracket x =
let braces = [ ('(', ')'); ('[', ']'); ('{', '}') ]
braces |> List.exists (fun (opening, _) -> opening = x)

let isClosingBracket x =
let braces = [ ('(', ')'); ('[', ']'); ('{', '}') ]
braces |> List.exists (fun (_, closing) -> closing = x)

let isBracePair x y =
let braces = [ ('(', ')'); ('[', ']'); ('{', '}') ]
List.contains (x, y) braces

let isBracketSequenceCorrect (str: string) =
let bracketPairs = [ ('(', ')'); ('[', ']'); ('{', '}') ]
let stack = System.Collections.Generic.Stack<char>()

str
|> Seq.forall (fun c ->
match c with
| '('
| '['
| '{' ->
stack.Push(c)
true
| ')'
| ']'
| '}' ->
if stack.Count = 0 then
false
else
let expected =
bracketPairs
|> List.tryFind (fun pair -> fst pair = stack.Peek())
|> Option.map snd

match expected with
| Some expectedChar when expectedChar = c ->
stack.Pop()
true
| _ -> false
| _ -> true)
&& stack.Count = 0
let rec helper (stack, seq) =
match seq with
| [] -> List.isEmpty stack
| first :: seqTail when isOpeningBracket first -> helper ((first :: stack), seqTail)
| first :: seqTail when isClosingBracket first ->
match stack with
| [] -> false
| top :: stackTail ->
if isBracePair top first then
helper (stackTail, seqTail)
else
false
| _ :: seqTail -> helper (stack, seqTail)

helper ([], Seq.toList str)



let str1 = "[a]"

let isBalanced1 = isBracketSequenceCorrect str1 // true


printfn "%A" $"{isBalanced1}"

0 comments on commit 99f7264

Please sign in to comment.