forked from dscgecbsp/Hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Anagram.java
48 lines (41 loc) · 1.1 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
// Problem statement
/*
Anagram--> The dictionary meaning of the word anagram is a word or phrase formed by rearranging the letters.
eg: HEART = EARTH
Approach:
First check the length, if not equal then discard it otherwise apply logic.
Pick a character from one list and check it with other if it is not visited then add it to list and check accordingly.
*/
import java.util.*;
public class Anagrams {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next(); // Add first string
String b = sc.next(); // Add second string
boolean isAnagram = false;
boolean visited[] = new boolean[b.length()];
if(a.length() == b.length()) {
for(int i = 0; i < a.length(); i++)
{
char c = a.charAt(i); // Pick a character from a
isAnagram = false;
for(int j = 0; j < b.length(); j++)
{
if(b.charAt(j) == c && !visited[j])
{
visited[j] = true;
isAnagram = true;
break;
}
}
if(!isAnagram)
break;
}
}
if(isAnagram)
System.out.println("anagram");
else
System.out.println("not anagram");
sc.close();
}
}