-
Notifications
You must be signed in to change notification settings - Fork 1
/
Anagram.java
75 lines (64 loc) · 1.67 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
package com.javamultiplex.string;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* @author Rohit Agarwal
* @category String Interview Questions
* @problem Check whether two Strings are anagram of each other or not.
*
*/
public class Anagram {
public static void main(String[] args) {
Scanner input=null;
try
{
input=new Scanner(System.in);
System.out.println("Enter first string: ");
String firstString=input.next();
System.out.println("Enter second string: ");
String secondString=input.next();
int firstStringLength=firstString.length();
int secondStringLength=secondString.length();
List<Character> firstList=new ArrayList<>();
List<Character> secondList=new ArrayList<>();
for(int i=0;i<firstStringLength;i++)
{
firstList.add(firstString.charAt(i)); //Converting First String to List
}
for(int i=0;i<secondStringLength;i++)
{
secondList.add(secondString.charAt(i)); //Converting Second String to List
}
if(isAnagram(firstList,secondList))
{
System.out.println("Anagram");
}
else
{
System.out.println("Not Anagram");
}
}
finally
{
if(input!=null)
{
input.close();
}
}
}
private static boolean isAnagram(List<Character> firstList, List<Character> secondList) {
int firstListSize=firstList.size();
int secondListSize=secondList.size();
boolean result=false;
if(firstListSize==secondListSize)
{
if(firstList.containsAll(secondList) && secondList.containsAll(firstList))
{
result=true;
}
}
return result;
}
}