August 10, 2018

Given strings are Anagram or not?

Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.
check-whether-two-strings-are-anagram-of-each-otherWe strongly recommend that you click here and practice it, before moving on to the solution.


Program:
public class Anagram {
public static void main(String[] args) {
String input1 = "d1asu";
String input2 = "adsu";
System.out.println("Given string are input1: " + input1 + ", input2: " + input2);
System.out.println("" + isAnagram(input1, input2));
}
private static String isAnagram(String input1, String input2) {
String result = "Given strings are not anagram";
boolean isAnagram = false;
if (!input1.isEmpty() && !input2.isEmpty() && (input1.length() == input2.length())) {
char[] arr = input1.toCharArray();
StringBuilder sb = new StringBuilder(input2);
for (char a : arr) {
int index = sb.indexOf("" + a);
if (index != -1) {
sb.deleteCharAt(sb.indexOf("" + a));
}
}
isAnagram = sb.toString().isEmpty();
}
if (!isAnagram) {
return result;
}
return "Given strings is anagram";
}
}
Output:
Given string are input1: d1asu, input2: adsu
Given strings are not anagram
Reference:
https://www.devglan.com/java-programs/anagram-test
https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/


No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts