Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
First, I have found common characters in both strings (intersection of characters) and calculate the count.
Then I haves substracted string one length and intersection chars count. Similar way substraction of string 2 length and intersection chars count.
The result is sum of these 2 substractions.
I created solution in:
All solutions are also available on my GitHub profile.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import scala.io.Source object Solution extends App { val lines = Source.stdin.getLines().toList val string1 = lines.head val string2 = lines.tail.head val commonChars = string1.intersect(string2) val toRemove = (string1.length - commonChars.length) + (string2.length - commonChars.length) println(toRemove) } |
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 28 29 30 |
import java.util.*; public class Solution { static int makingAnagrams(String str1, String str2) { int[] counts1 = new int[256]; int[] counts2 = new int[256]; for(int i=0; i < str1.length(); i++) { int index = (int)(str1.charAt(i)); counts1[index] += 1; } for(int i=0; i < str2.length(); i++) { int index = (int)(str2.charAt(i)); counts2[index] += 1; } int ans = 0; for(int i=0; i < 256; i++) { ans += Math.abs(counts1[i] - counts2[i]); } return ans; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1 = in.next(); String s2 = in.next(); int result = makingAnagrams(s1, s2); System.out.println(result); } } |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
process.stdin.resume(); process.stdin.setEncoding('ascii'); var input_stdin = ""; var input_stdin_array = ""; var input_currentline = 0; process.stdin.on('data', function (data) { input_stdin += data; }); process.stdin.on('end', function () { input_stdin_array = input_stdin.split("\n"); main(); }); function readLine() { return input_stdin_array[input_currentline++]; } /////////////// ignore above this line //////////////////// function makingAnagrams(s1, s2){ var letters = Array.apply(null, new Array(26)).map(Number.prototype.valueOf,0); assignWeight(letters,s1,1); assignWeight(letters,s2,-1); var solution = letters.reduce(function(prev, curr){ return Math.abs(prev) + Math.abs(curr); }); return solution; } function assignWeight(letters, word, weigth) { var charCode; for (var i = 0;i < word.length; i++){ charCode = word.charCodeAt(i) - 97; letters[charCode] += weigth; } } function main() { var s1 = readLine(); var s2 = readLine(); var result = makingAnagrams(s1, s2); process.stdout.write("" + result + "\n"); } |