Hackerrank – Beautiful Binary String
Hackerrank – Problem Statement A description of the problem can be found on Hackerrank. Solution I replaced all occurences of “010” with an arbitrary placeholder. Then I counted the placeholders. I created solution in: Scala Java JavaScript Ruby All solutions are also available on my GitHub. Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.*; public class BeautifulBinaryString { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int l = Integer.parseInt(stdin.nextLine()); String s = stdin.nextLine(); String beautiful = s.replaceAll("010", "b"); int changes = beautiful.replaceAll("[01]", "").length(); System.out.println(changes); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
'use strict'; const processData = input => { const lines = input.split('\n'); const s = lines[1]; const beautiful = s.replace(/010/g, "b"); const changes = beautiful.replace(/[01]/g, "").length; console.log(changes); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 |
object BeautifulBinaryString { def main(args: Array[String]) { val sc = new java.util.Scanner (System.in) val n = sc.nextInt() val B = sc.next() val beautiful = B.replaceAll("010", "b") val changes = beautiful.count(_ == 'b') println(changes) } } |
Ruby
1 2 3 4 5 6 |
l = gets.to_i s = gets.to_s.strip s.gsub!(/010/, "b") s.gsub!(/[01]/, "") puts s.length() |