Created
February 1, 2021 14:05
-
-
Save akashkumarcs19/f8d9b90d6570a9ad3fc277ef11278be1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Scanner; | |
class Anagram { | |
public static void main(String[] args) { | |
Scanner s = new Scanner(System.in); | |
System.out.println("Enter the First string: "); | |
String st = s.nextLine(); | |
System.out.println("Enter the Second string: "); | |
String s1 = s.nextLine(); | |
if(st.length()==s1.length()){ | |
if(checkAnagram(st,s1)==true){ | |
System.out.println("String are Anagrams"); | |
} | |
if(!checkAnagram(st,s1)) | |
System.out.println("Strings are not Anagrams"); | |
} | |
} | |
static boolean checkAnagram(String st, String s1) { | |
char[] c1 = st.toCharArray(); | |
char[] c2 = s1.toCharArray(); | |
HashMap<Character, Integer> hashMap = new HashMap<>(); | |
for (int i=0 ;i<c1.length;i++) { | |
int count = 0; | |
if (hashMap.containsKey(c1[i])) { | |
count = hashMap.get(c1[i]); | |
} | |
hashMap.put(c1[i], count += 1); | |
count=0; | |
if (hashMap.containsKey(c2[i])) { | |
count = hashMap.get(c2[i]); | |
} | |
hashMap.put(c2[i], count -= 1); | |
} | |
for (int j : hashMap.values()) { | |
if (j != 0) | |
return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment