Monday, August 31, 2015

Strings are permutations?

Problem

Find out if 2 strings are permutations of each other.

Solution

 private HashMap convertStringToMap(String s)
 {
  HashMap map = new HashMap();
  Integer mapValue;
  Character c;
  for(int i=0; i< s.length(); i++)
  {
   c = s.charAt(i);
   mapValue = map.get(c);
   if(mapValue == null) map.put(c, 1);
   else map.put(c, mapValue+1);
  }
  return map;
 }

 private boolean permutation(String string1, String string2) {

  if(string1.length() != string2.length()) return false;

  HashMap map1 = convertStringToMap(string1);
  HashMap map2 = convertStringToMap(string2);

  return map1.equals(map2);
 }


No comments:

Post a Comment