-
Notifications
You must be signed in to change notification settings - Fork 0
/
Anagram.java
107 lines (78 loc) · 2.74 KB
/
Anagram.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.io.*;
import java.util.*;
public class Anagram
{
private static final byte ALPHABET_LENGTH = 26;
private static final byte ASCII_ALPHABET_OFFSET = 97;
public static void main(String[] args) throws IOException
{
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(byte T = Byte.parseByte(br.readLine()); T > 0; --T)
{
short numChanges = -1;
char[] ab = br.readLine().toCharArray();
short max = (short)ab.length;
if((max & 1) == 0)
{
numChanges = 0;
short mid = (short)(max >> 1);
short[] map = new short[ALPHABET_LENGTH];
for(short i = mid; i < max; map[ab[i++] - ASCII_ALPHABET_OFFSET]++){}
for(short i = 0; i < mid; numChanges += (map[ab[i++] - ASCII_ALPHABET_OFFSET]-- > 0) ? 0 : 1){}
}
sb.append(numChanges + "\n");
}
System.out.print(sb);
}
}
/*
public class Anagram
{
static void isAnagram(String s1, String s2)
{
//Removing all white spaces from s1 and s2
String copyOfs1 = s1.replaceAll("\\s", "");
String copyOfs2 = s2.replaceAll("\\s", "");
//Initially setting status as true
boolean status = true;
if(copyOfs1.length() != copyOfs2.length())
{
//Setting status as false if copyOfs1 and copyOfs2 doesn't have same length
status = false;
}
else
{
//Changing the case of characters of both copyOfs1 and copyOfs2 and converting them to char array
char[] s1Array = copyOfs1.toLowerCase().toCharArray();
char[] s2Array = copyOfs2.toLowerCase().toCharArray();
//Sorting both s1Array and s2Array
Arrays.sort(s1Array);
Arrays.sort(s2Array);
//Checking whether s1Array and s2Array are equal
status = Arrays.equals(s1Array, s2Array);
}
//Output
if(status)
{
System.out.println(s1+" and "+s2+" are anagrams");
}
else
{
System.out.println(s1+" and "+s2+" are not anagrams");
}
}
public static void main(String[] args)
{
isAnagram("Mother In Law", "Hitler Woman");
isAnagram("keEp", "peeK");
isAnagram("SiLeNt CAT", "LisTen AcT");
isAnagram("Debit Card", "Bad Credit");
isAnagram("School MASTER", "The ClassROOM");
isAnagram("DORMITORY", "Dirty Room");
isAnagram("ASTRONOMERS", "NO MORE STARS");
isAnagram("Toss", "Shot");
isAnagram("joy", "enjoy");
}
}
*/