Hackerrank – Java Solution – Java Anagrams Solution

Hackerrank - Java Solutions Hackerrank Online Judge Solution

Hackerrank – Java Solution – Java Anagrams Solution

Problem Name – Java Anagrams
Problem Link –  Java Anagrams 
Level – String

Java Anagram Full Code

mport java.io.*;
import java.util.*;

public class Solution {
static boolean isAnagram(String a, String b) {
if ((a == null || b == null) || (a.length() != b.length())) {
return false;
}
final char[] ARRAY_A = a.toUpperCase().toCharArray();
final Map map = new HashMap<>();
for (int i = 0; i < ARRAY_A.length; i ++) {
if (map.containsKey(ARRAY_A[i])) {
map.put(ARRAY_A[i], (map.get(ARRAY_A[i]) + 1));
} else {
map.put(ARRAY_A[i], 1);
}
}
final char[] ARRAY_B = b.toUpperCase().toCharArray();
for (int i = 0; i < ARRAY_A.length; i ++) {
if (map.containsKey(ARRAY_B[i])) {
Integer count = map.get(ARRAY_B[i]);
if (count == 0) {
return false;
} else {
count --;
map.put(ARRAY_B[i], count);
}
} 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" );
}
}

Java Anagram Only Submitted Code

static boolean isAnagram(String a, String b) {
if ((a == null || b == null) || (a.length() != b.length())) {
return false;
}
final char[] ARRAY_A = a.toUpperCase().toCharArray();
final Map map = new HashMap<>();
for (int i = 0; i < ARRAY_A.length; i ++) {
if (map.containsKey(ARRAY_A[i])) {
map.put(ARRAY_A[i], (map.get(ARRAY_A[i]) + 1));
} else {
map.put(ARRAY_A[i], 1);
}
}
final char[] ARRAY_B = b.toUpperCase().toCharArray();
for (int i = 0; i < ARRAY_A.length; i ++) {
if (map.containsKey(ARRAY_B[i])) {
Integer count = map.get(ARRAY_B[i]);
if (count == 0) {
return false;
} else {
count --;
map.put(ARRAY_B[i], count);
}
} else {
return false;
}
}
return true;
}


Output: 

Hackerrank - Java Solution - Java Anagrams Solution

Tags: HackerRank Online Judge Solution, HackerRank OJ Solution list, HackerRank Problems Solution, HackerRank solver, HackerRank all problem solution list, HackerRank solution in java, Hackerrank Java Solution, Hackerrank – Java Solution – Java Anagrams Solution, Hackerrank Online Judge Solution, Hackerrank – Java Solutions,

Leave a Reply

Your email address will not be published.