Skip to content

Instantly share code, notes, and snippets.

@bipiane
Created August 12, 2020 21:08
Show Gist options
  • Save bipiane/ff4c8378231eb55618dcf0316bf340b2 to your computer and use it in GitHub Desktop.
Save bipiane/ff4c8378231eb55618dcf0316bf340b2 to your computer and use it in GitHub Desktop.
isValidBinaryString
def isValidBinaryString(String list) {
def total = list?.size()
// TODO check one or more 0's or 1's with regex: \[0|1]+\g 🤔
if (total == 0 || total % 2 != 0) {
return false
}
// The number of 0's is equal to the number of 1's.
if (list.findAll { it == '1' }?.size() != list.findAll { it == '0' }?.size()) {
return false
}
// For every prefix of the binary string, the number of 1's should not be less than the number of 0's
(0..(total - 1)).each {
def prefix = list[0..it]
if (prefix.findAll { it == '1' }?.size() >= prefix.findAll { it != '1' }?.size()) {
return false
}
}
true
}
println 'A- test 11010: ' + isValidBinaryString('11010') //false
println 'B- test 110010: ' + isValidBinaryString('110010')//true
println 'C- test empty: ' + isValidBinaryString('')//false
println 'C- test 110x10: ' + isValidBinaryString('110x10')//false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment