Files

46 lines
1.3 KiB
Java
Raw Permalink Normal View History

2017-02-12 00:31:12 -08:00
// Author: Rodney Shaghoulian
2018-07-27 16:45:56 -07:00
// Github: github.com/RodneyShag
// HackerRank: hackerrank.com/RodneyShag
2017-02-12 00:31:12 -08:00
2017-02-07 01:14:49 -08:00
import java.io.*;
import java.util.*;
public class Solution {
2017-04-05 18:42:35 -05:00
// Time Complexity: O(n) using a HashMap
// Space Complexity: O(n)
2017-02-07 01:14:49 -08:00
static boolean isAnagram(String a, String b) {
if (a == null || b == null || a.length() != b.length()) {
return false;
}
a = a.toLowerCase();
b = b.toLowerCase();
HashMap<Character, Integer> map = new HashMap<>();
/* Fill HashMap with 1st String */
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
2017-03-18 22:17:22 -05:00
map.merge(ch, 1, Integer::sum);
2017-02-07 01:14:49 -08:00
}
/* Compare 2nd String to 1st String's HashMap */
for (int i = 0; i < b.length(); i++) {
char ch = b.charAt(i);
if (map.containsKey(ch) && map.get(ch) > 0) {
map.put(ch, map.get(ch) - 1);
} else {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}