Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Rozdelil som zadaný reťazec na 2 polovice a spočítal som spoločné znaky v obidvoch poloviciach. Výsledok je rozdiel medzi dĺžkou 1. polovice (alebo 2.) a počtom spoločných znakov.
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
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 } } } |