hanCodeHub
3/13/2020 - 10:42 PM

Check String Permutation

Given two strings, write a method to check if one is a permutation of the other. No need to check for case.

Algorithm:

  1. hashmap counts char occurrences from string 1
  2. loop over string 1 and increment occurrences
  3. loop over string 2 and decrement occurences (return false if not found)
  4. loop over the map values and check if each one is zeroed out
static boolean isPermutation(String str1, String str2) {
        if (str1.length() != str2.length()) return false;
        if (str1.length() == 0 && str2.length() == 0) return true;

        HashMap<Character, Integer> map = new HashMap<>();

        // increment all chars from string 1
        for (int i = 0; i < str1.length(); i++) {
            char c = str1.charAt(i);
            if (map.containsKey(c)) {
                int val = map.get(c);
                map.put(c, ++val);
            } else {
                map.put(c, 1);
            }
        }

        // decrement all chars from string 2
        for (int i = 0; i < str2.length(); i++) {
            char c = str2.charAt(i);
            if (!map.containsKey(c)) return false;
            int val = map.get(c);
            map.put(c, --val);
        }

        // check if all values are zeroed out
        for (int val : map.values()) {
            if (val != 0) return false;
        }

        return true;
    }