Skip to content

Instantly share code, notes, and snippets.

@m-sedl
Last active September 10, 2021 20:35
Show Gist options
  • Save m-sedl/77896b717bd2e88d12921675399a1bf0 to your computer and use it in GitHub Desktop.
Save m-sedl/77896b717bd2e88d12921675399a1bf0 to your computer and use it in GitHub Desktop.
let isCorrectBracketsSeq (str: string) =
let getNewBalance balance char =
if balance < 0 then
balance
else
balance + match char with
| '(' -> 1
| ')' -> -1
| _ -> 0
List.fold getNewBalance 0 (Seq.toList str) = 0
[<EntryPoint>]
let main argv =
printfn "%b" (isCorrectBracketsSeq "((()))") // true
printfn "%b" (isCorrectBracketsSeq "qwerty(((())))((7 + 8))(((()))()())") // true
printfn "%b" (isCorrectBracketsSeq "(()))") // false
printfn "%b" (isCorrectBracketsSeq ")))(((") // false
printfn "%b" (isCorrectBracketsSeq "))()(") // false
0
fun main() {
println("2 * (3(5 -8))(10 - 7)(-(8 + (34) - 9) + 6)".isCorrectBracketsSeq())
println(")(".isCorrectBracketsSeq())
println("(()(".isCorrectBracketsSeq())
}
fun String.isCorrectBracketsSeq(): Boolean {
return 0 == this.fold(0) { balance, it ->
if (balance < 0) return false
balance + when (it) {
'(' -> 1
')' -> -1
else -> 0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment