Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I created an accumulator with initial value as empty string. I iterated through each character and updated the accumulator
- if an actual character is equals to last accumulator character, delete this character from the accumulator
- else append the character to the accumulator
The result is the accumulator after the iteration.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.*; public class SuperReducedString { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); String s = stdin.nextLine(); String acc = ""; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(acc.length() > 0 && acc.charAt(acc.length() - 1) == c) { acc = acc.substring(0, acc.length() - 1); } else { acc += c; } } System.out.println(acc.isEmpty() ? "Empty String" : acc); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
'use strict'; const processData = input => { const line = input.split('\n')[0]; let acc = ""; for(let i = 0; i < line.length; i++) { const c = line[i]; if(acc.length > 0 && acc[acc.length - 1] === c) { acc = acc.slice(0, acc.length - 1); } else { acc += c; } } console.log(acc.length === 0 ? "Empty String" : acc); }; 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 |
import scala.io.Source object SuperReducedString extends App { val line = Source.stdin.getLines().toList.head val reduced = line.foldLeft("")(stringReduce) println(if(reduced.isEmpty) "Empty String" else reduced) def stringReduce(acc: String, c: Char): String = { if(acc.length > 0 && acc.charAt(acc.length - 1) == c) acc.substring(0, acc.length - 1) else acc + c } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
s = gets.strip acc = "" for i in 0...(s.length) do c = s[i] if(acc.length > 0 && acc[acc.length - 1] == c) acc = acc.slice(0, acc.length - 1) else acc = acc + c end end if(acc.length == 0) puts "Empty String" else puts acc end |