-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c76e43f
commit 99f7264
Showing
1 changed file
with
39 additions
and
29 deletions.
There are no files selected for viewing
This file contains 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
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}" |