Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Divide the input string into two halves. Count all common character in the halves. A result is difference between length of the one half and count of the common characters.
Different solution deletes common characters from the second half. The result is length of the second half after deletions.
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 21 22 23 24 25 26 27 |
import java.util.Scanner; public class Anagram { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); for(int i = 0; i < tests; i++) { String s = stdin.next(); System.out.println(deletions(s)); } stdin.close(); } private static int deletions(String s) { if(s.length() % 2 != 0) { return -1; } String half1 = s.substring(0, s.length() / 2); String half2 = s.substring(s.length() / 2); for(int i = 0; i < half1.length(); i++) { if(half2.contains(half1.substring(i, i + 1))) { half2 = half2.replaceFirst(half1.substring(i, i + 1), ""); } } return half2.length(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function processData(input) { var lines = input.split("\n"); console.log(lines.slice(1).map(deletions).join('\n')); } function deletions(s) { if(s.length % 2 != 0) { return -1; } var h1 = s.substring(0, s.length / 2); var h2 = s.substring(s.length / 2); for(var i = 0; i < h1.length; i++) { if(h2.indexOf[h1[i]] !== -1) { h2 = h2.replace(h1[i], ''); } } return h2.length; } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
def substitutions(input) half1 = input.slice(0, input.length / 2) half2 = input.slice(input.length / 2, input.length) for i in 0..half1.length - 1 do half2.sub!(half1[i], "") if half2.include?(half1[i]) end return half2.length end tests = gets.chomp.to_i tests.times do input = gets.chomp result = 0 if input.length % 2 != 0 result = -1 else result = substitutions(input) end puts result end |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import scala.io.Source object Anagram extends App { val strings = Source.stdin.getLines().drop(1) val charsToDelete = strings.map(numOfChanges) println(charsToDelete.mkString("\n")) def numOfChanges(s: String): Int = { if (s.length % 2 != 0) -1 else { val half1 = s.substring(0, s.length / 2) val half2 = s.substring(s.length / 2) half1.length - half1.intersect(half2).length } } } |