fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class solution {
  9. public static void main(String[] args){
  10. String s = "anfefeg"; // true
  11. String t = "fegafen";
  12. System.out.println(isAnagram(s,t));
  13. }
  14. public static boolean isAnagram(String s, String t) {
  15. defaultHashMap<Character, Integer> countS = new defaultHashMap<>(0);
  16. defaultHashMap<Character, Integer> countT = new defaultHashMap<>(0);
  17. if (s.length() != t.length()){
  18. return false;
  19. }
  20. // count frequencies of characters
  21. for (int i=0; i < s.length(); i++){
  22. countS.put(s.charAt(i), countS.get(s.charAt(i)) + 1);
  23. countT.put(t.charAt(i), countT.get(t.charAt(i)) + 1);
  24. }
  25. // System.out.println(countS.entrySet());
  26. // System.out.println(countT.entrySet());
  27.  
  28. // compare to map
  29. for (Map.Entry<Character, Integer> entry : countT.entrySet()){
  30. if (entry.getValue() != countS.get(entry.getKey())){
  31. return false;
  32. }
  33. }
  34. return true;
  35. }
  36. }
  37. /*
  38. define a defaultHashMap class extending hashmap
  39. */
  40. class defaultHashMap <K,V> extends HashMap<K,V> {
  41. protected V defaultValue;
  42. public defaultHashMap(V defaultValue) {
  43. this.defaultValue = defaultValue;
  44. }
  45. @Override
  46. public V get(Object k) {
  47. return containsKey(k) ? super.get(k) : defaultValue;
  48. }
  49.  
  50. }
Success #stdin #stdout 0.1s 27760KB
stdin
Standard input is empty
stdout
true