Given two strings, check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “act” and “tac” are anagram of each other.
Input:
The first line of input contains an integer T denoting the number of test cases. Each test case consist of two strings in 'lowercase' only, in a separate line.
Output:
Print "YES" without quotes if the two strings are anagram else print "NO".
Constraints:
1 ≤ T ≤ 30
1 ≤ |s| ≤ 100
Example:
Input:
2
geeksforgeeks
forgeeksgeeks
allergy
allergic
Output:
YES
NO
My approach:
/*package whatever //do not write package name here */
import java.util.Scanner;
import java.io.IOException;
import java.util.HashMap;
class GFG {
private static String isAnagram (String str1, String str2)
{
HashMap <Character, Integer>occurs = new HashMap<>();
if (str1.length() != str2.length())
{
return "NO";
}
for (char ch: str1.toCharArray())
{
if (!(occurs.containsKey(ch)))
{
occurs.put(ch,1);
}
else
{
int count = occurs.get(ch);
occurs.put(ch,count + 1);
}
}
for (char ch: str2.toCharArray())
{
if (!(occurs.containsKey(ch)))
{
return "NO";
}
else
{
int count = occurs.get(ch);
count = count - 1;
if (count < 0)
{
return "NO";
}
else
{
occurs.put(ch,count);
}
}
}
return "YES";
}
public static void main (String[] args) throws IOException {
Scanner sc = new Scanner (System.in);
int numTests = sc.nextInt();
for (int i = 0; i < numTests; i++)
{
String str1 = sc.next();
String str2 = sc.next();
System.out.println(isAnagram(str1, str2));
}
}
}
I have the following questions with regards to the above code:
1) How can I further improve my approach?
2) Is there a better way to solve this question?
3) Are there any grave code violations that I have committed?
4) Can space and time complexity be further improved?