Check if Strings are Permutations – JAVA Program Source Code


The following program verifies if 2 input strings are permutations of each other and displays the result.

Source Code:

package javasamples;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class JavaSamples 
{
 public static HashMap CreateStringHash(String s)
 {
 HashMap mapStr = new HashMap();
 char str[] = s.toCharArray();
 int i = 1;
 for(char c : str)
 {
 if(mapStr.get(c)==null)
 mapStr.put(c,i);
 else
 {
 mapStr.put(c,i+(int)mapStr.get(c));
 }
 }
 return(mapStr);
 }
 public static boolean CheckStringPerm(String s1, String s2)
 {
 HashMap mapStr1 = CreateStringHash(s1);
 char str2[] = s2.toCharArray();
 for(char c : str2)
 {
 if(mapStr1.get(c)==null || (int)mapStr1.get(c)==0)
 return(false);
 else
 mapStr1.put(c,(int)mapStr1.get(c)-1);
 }
 Iterator itr = mapStr1.entrySet().iterator();
 Map.Entry strEntry;
 while(itr.hasNext())
 {
 strEntry = (Map.Entry) itr.next();
 if((int)strEntry.getValue()!=0)
 return(false);
 }
 return(true);
 }
 public static void main(String[] args) 
 {
 String str1 = "Elephants are great";
 String str2 = "great Elephant arse";
 System.out.println("String1 = " + str1);
 System.out.println("String2 = " + str2);
 System.out.print("Strings are Permutation = ");
 if(CheckStringPerm(str1,str2))
 System.out.println("Yes");
 else
 System.out.println("No");
 }
}

OUTPUT:

run:
String1 = Elephants are great
String2 = great Elephant arse
Strings are Permutation = Yes
BUILD SUCCESSFUL (total time: 0 seconds)

6 thoughts on “Check if Strings are Permutations – JAVA Program Source Code

  1. Greetings from Florida! I’m bored to tears at work so I decided to browse your website on my iphone during lunch break. I love the info you present here and can’t wait to take a
    look when I get home. I’m surprised at how quick your blog loaded on my phone .. I’m not even using WIFI, just 3G .

    . Anyhow, fantastic blog!

Leave a comment