fork 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 Ideone
  9. {
  10. public static boolean isAnagram(String s, String t) {
  11. if (s.length() != t.length()) return false;
  12.  
  13. HashMap<Character, Integer> map = new HashMap<>();
  14.  
  15. // Count frequency of each character in string s
  16. for (char c : s.toCharArray()) {
  17. map.put(c, map.getOrDefault(c, 0) + 1);
  18. }
  19.  
  20. // Subtract frequency using string t
  21. for (char c : t.toCharArray()) {
  22. if (!map.containsKey(c)) return false;
  23. map.put(c, map.get(c) - 1);
  24. if (map.get(c) == 0) map.remove(c);
  25. }
  26.  
  27. // If map is empty, it's a valid anagram
  28. return map.isEmpty();
  29. }
  30.  
  31. public static void main(String[] args) {
  32. System.out.println(isAnagram("listen", "silent")); // true
  33. System.out.println(isAnagram("hello", "world")); // false
  34. }
  35. }
  36.  
  37.  
Success #stdin #stdout 0.08s 54896KB
stdin
Standard input is empty
stdout
true
false