Last active
September 10, 2021 20:35
-
-
Save m-sedl/77896b717bd2e88d12921675399a1bf0 to your computer and use it in GitHub Desktop.
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
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 |
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
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