You need to sign in to do that
Don't have an account?
Rahul Rana 32
Anagram program in Apex
Hi Salesforce Experts,
Could you please tell me how to write a program to check if two strings are anagram of each other in Apex?
Thanks in Advance.
Could you please tell me how to write a program to check if two strings are anagram of each other in Apex?
Thanks in Advance.
Try this code
Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.
Thanks and Regards
All Answers
Try this code
Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.
Thanks and Regards
You can utilize the below code if you want to find and print all anagrams in a given string. Please copy-paste below code in anonymous window to test.
//creating anagram input data.
List<String> inputArray = new List<String>{'cat', 'dog', 'tac', 'god', 'act'};
//Code to check every two combinations of input array
Map<Integer,Set<Integer>> mp = new Map<Integer,Set<Integer>>();
for(Integer i=0;i<inputArray.size();i++){
for(Integer j=i+1;j<inputArray.size();j++){
IsAnagram(inputArray[i],inputArray[j]);
}
}
//Code to print Result
system.debug('res1>'+mp);
for(Integer i :mp.keyset()){
Set<Integer> templist1 = mp.get(i);
for(Integer j :templist1){
system.debug('Result>'+inputArray.get(j));
}
}
//Method to check if two numbers are anagram and store them using hashcode to print together later
public Boolean IsAnagram(String a, String b){
Boolean isAna = False;
if(a.length() == b.length())
{
string[] sarray1 = a.split('');
string[] sarray2 = b.split('');
sarray1.sort();
sarray2.sort();
if(sarray1 == sarray2){
isAna = True;
string temps1 = String.join(sarray1,'');
string temps2 = String.join(sarray2,'');
Integer h1 = temps1.hashcode();
Integer h2 = temps1.hashcode();
if(mp.containsKey(h1)) {
Set<Integer> index = mp.get(h1);
index.add(inputArray.indexOf(a));index.add(inputArray.indexOf(b));
mp.put(h1, index);
} else {
Integer x = inputArray.indexOf(a);
Integer y = inputArray.indexOf(b);
mp.put(h1, new Set<Integer> {x,y});
}
}
}
return isAna;
}