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
|
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
|
'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
|
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
|
l = gets.to_i s = gets.to_s.strip s.gsub!(/010/, "b") s.gsub!(/[01]/, "") puts s.length() |