We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Very nice and neat! Here is my C# implementation off the same algorythm.
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;classSolution{staticvoidMain(String[]args){// reading the two strings we need to evaulatestringa=Console.ReadLine();stringb=Console.ReadLine();// to work with the input strings we// convert them into arrayschar[]string1=a.ToCharArray();char[]string2=b.ToCharArray();// set the final result counter to 0// so we can use it at the endintresult=0;// Set a dictionary / hash table with which we// are going to track occurrencies of characters// in string1 and and string2 arrays// in C++, the equivalent of the dictionary below,// as cool_shark did, would look neater:// vector<int> freq(26, 0);// If perhaps someone has a niftier way o// implementing the data structure below, please,// let me know. Dictionary<char,int>frequencyDictionary=newDictionary<char,int>(){{'a',0},{'b',0},{'c',0},{'d',0},{'e',0},{'f',0},{'g',0},{'h',0},{'i',0},{'j',0},{'k',0},{'l',0},{'m',0},{'n',0},{'o',0},{'p',0},{'q',0},{'r',0},{'s',0},{'t',0},{'u',0},{'v',0},{'w',0},{'x',0},{'y',0},{'z',0}};// go through the second string array and note// down the into the dictionary the number// of occurrence of each character by adding// 1 for each characterfor(inti=0;i<string1.Length;i++){charchr=string1[i];frequencyDictionary[chr]++;}// go through the second string array and note down// the into the dictionary the number// of occurrence of each character by subtracting// 1 for each characterfor(inti=0;i<string2.Length;i++){charchr=string2[i];frequencyDictionary[chr]--;}// At this point the dictionary should store numbers// we need to calculate our final result.// If for any key (our keys are// lowercase characters of the alphabet) // in the dictionary, the number is smaller or// greater than 0,// this means, that that is actually the character// that needs to be removed.// And it needs to ne removed (from either of// the original strings)// as many times as the absolute value of the number.// let us calculate the number of characters that we// need to remove from both// of the original strings.foreach(varpairinfrequencyDictionary){// if a character appears one or more times// in the second string // but it does not appear in the first string at// all, then the number// will be negative, thus we need to make it// absolute when we calculate// the final numberresult+=Math.Abs(pair.Value);}Console.Write(result);}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Strings: Making Anagrams
You are viewing a single comment's thread. Return to all comments →
Very nice and neat! Here is my C# implementation off the same algorythm.