bozhilov

Anagrams O(n)

Mar 13th, 2022 (edited)
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Scanner;
  4.  
  5. public class Solution {
  6.     static boolean isAnagram(String a, String b) {
  7.         Map<Character, Integer> dictionary = new HashMap<Character, Integer>();
  8.         a = a.toLowerCase();
  9.         b = b.toLowerCase();
  10.        
  11.         for (int i = 0; i < a.length(); i++) {
  12.             if(!dictionary.containsKey(a.charAt(i))){
  13.                 dictionary.put(a.charAt(i), 1);
  14.             } else {
  15.                 dictionary.replace(a.charAt(i), dictionary.get(a.charAt(i)) + 1);
  16.             }
  17.         }
  18.         for (int y = 0; y < b.length(); y++) {
  19.             if(!dictionary.containsKey(b.charAt(y))){
  20.                 return false;
  21.             } else {
  22.                 dictionary.replace(b.charAt(y), dictionary.get(b.charAt(y)) - 1);
  23.             }
  24.         }
  25.         for(Map.Entry<Character, Integer> entry: dictionary.entrySet()){
  26.             if(entry.getValue()!=0){
  27.                 return false;
  28.             }
  29.         }
  30.         return true;
  31.     }
  32.  
  33.     public static void main(String[] args){
  34.         Scanner scanner = new Scanner(System.in);
  35.         String a = scanner.nextLine();
  36.         String b = scanner.nextLine();
  37.         scanner.close();
  38.  
  39.         System.out.println(isAnagram(a, b)?"Anagrams":"Not Anagrams");
  40.     }
  41. }
Add Comment
Please, Sign In to add comment