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.
Strings: Making Anagrams
Strings: Making Anagrams
+ 0 comments My solution in c++.
int number_needed(string a, string b) { auto count = 0; vector<int> freq(26, 0); for (auto c : a) { ++freq[c - 'a']; } for (auto c : b) { --freq[c - 'a']; } for (auto val : freq) { count += abs(val); } return count; }
+ 0 comments It appears to me my python solution is much better then the one posted in editorial:
from collections import Counter def number_needed(a, b): ct_a = Counter(a) ct_b = Counter(b) ct_a.subtract(ct_b) return sum(abs(i) for i in ct_a.values())
Cons?
+ 0 comments For Java there was an error in the given code. I needed to change the arguments for numberNeeded from (first, second) to (a, b).
+ 0 comments My solution is...
public class Solution { public static int numberNeeded(String first, String second) { Map<Character, Integer> count = new HashMap<>(); for( char ch: first.toCharArray() ) { int ct = count.containsKey(ch) ? count.get(ch) : 0; count.put(ch, (ct + 1)); } for( char ch: second.toCharArray() ) { int ct = count.containsKey(ch) ? count.get(ch) : 0; count.put(ch, (ct - 1)); } List<Integer> values = new ArrayList<>( count.values() ); int total = 0; for( Integer v: values ) { total += Math.abs(v); } return total; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.next(); String b = in.next(); System.out.println(numberNeeded(a, b)); } }
+ 0 comments Solution in O(M+N) using a dictionary. Detailed explanation here: Anagrams explanation
def number_needed(str1, str2): dict_chars = dict() for char in str1: if char in dict_chars: dict_chars[char] += 1 else: dict_chars[char] = 1 for char in str2: if char in dict_chars: dict_chars[char] -= 1 else: dict_chars[char] = -1 sum_diff = 0 for char in dict_chars.keys(): sum_diff += abs(dict_chars[char]) return sum_diff a = input().strip() b = input().strip() print(number_needed(a, b))
Load more conversations
Sort 1809 Discussions, By:
Please Login in order to post a comment