-
Notifications
You must be signed in to change notification settings - Fork 0
/
Java-Anagrams.java
76 lines (71 loc) · 2.21 KB
/
Java-Anagrams.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.Scanner;
public class Solution {
static boolean isAnagram(String a, String b) {
// Complete the function
boolean flag = false;
//counting frequency of characters in first string
int[] freq_a = new int[a.length()];
char[] char_a = a.toCharArray();
for(int i=0;i<a.length();i++)
{
freq_a[i]=1;
for(int j=i+1;j<a.length();j++)
{
if(Character.toLowerCase(char_a[i])==Character.toLowerCase(char_a[j]))
{
freq_a[i]=freq_a[i]+1;
char_a[j]='0';
}
}
}
//counting frequency of characters in second string
int[] freq_b = new int[b.length()];
char[] char_b = b.toCharArray();
for(int i=0;i<b.length();i++)
{
freq_b[i]=1;
for(int j=i+1;j<b.length();j++)
{
if(Character.toLowerCase(char_b[i])==Character.toLowerCase(char_b[j]))
{
freq_b[i]=freq_b[i]+1;
char_b[j]='0';
}
}
}
//compare frequency of both strings characters
if(char_a.length==char_b.length)
{
for(int l=0;l<char_a.length;l++)
{
for(int k=0;k<char_b.length;k++)
{
if(char_a[l]!='0' && char_b[k]!='0' && Character.toLowerCase(char_a[l])==Character.toLowerCase(char_b[k]))
{
if(freq_a[l]==freq_b[k])
{
flag = true;
}
else
{
return false;
}
}
}
}
}
else
{
return false;
}
return flag;
}
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" );
}
}