Q21 PepCoding | K Anagrams
Thu Jan 26 2023 08:22:10 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
import java.util.*;
public class Main {
public static boolean areKAnagrams(String str1, String str2, int k) {
//check if characters are equal
if(str1.length()!=str2.length())
return false;
//make frequency map of any 1 string
HashMap<Character,Integer> map = new HashMap<>();
for(int i= 0 ;i < str1.length();i++){
char ch = str1.charAt(i);
map.put(ch , map.getOrDefault(ch,0)+1);
}
//now traverse the 2nd string and start removing from HM
for(int i =0 ; i< str2.length();i++){
char ch = str2.charAt(i);
if(map.getOrDefault(ch,0) >0)
map.put(ch , map.get(ch)-1);
}
//add all positive frequency
int count = 0 ;
for(char ch : map.keySet())
count+= map.get(ch);
return count >k ? false : true;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str1 = s.next();
String str2 = s.next();
int k = s.nextInt();
System.out.println(areKAnagrams(str1, str2, k));
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/k-anagrams-official/ojquestion
Comments